我正在尝试测试一个spring引导服务,它同时依赖于一个存储库和另一个服务。我使用testcontainers来验证服务是否与存储库正确交互。但是,我需要模拟其他服务,以便提供将要使用的测试数据。所讨论的服务方法需要是事务性的。
@Service
public class MyService {
private MyRepository myRepository; // This needs to be a real repository
private OtherService otherService; // This needs to be mocked
@Autowired
public MyService(MyRepository myRepository, OtherService otherService) {...}
@Transactional
public void methodToTest() {
// Get (mock) data from otherService, and interact with (real) myRepository
}
}
我可以通过手动创建带有依赖项的服务,让它在测试中正常工作。但是,生成的对象只是一个pojo,它没有被spring增强 Transactional
:
@SpringBootTest
@ContextConfiguration(initializers = {TestContainersConfig.class})
public class MyServiceTest {
@Autowired
MyRepository myRepository;
OtherService otherService;
MyService myService;
@BeforeEach
void setup() {
otherService = Mockito.mock(OtherService.class);
// This works, except that the object is a POJO and so @Transactional doesn't work
myService = new MyService(myRepository, otherService);
}
@Test
@Transactional
void testMethodToTest() {
// Provide mock data
when(otherSerivce.something()).thenReturn(...);
// Run the test
myService.methodToTest();
// Would like to remove these lines: myService should already do it
TestTransaction.flagForCommit();
TestTransaction.end();
// assertions...
}
}
如何让spring增强测试 MyService
举例说明 methodToTest
你会处理这笔交易吗?
暂无答案!
目前还没有任何答案,快来回答吧!