如何在常规的 Spring 框架项目中使用 @SpyBean 和 @MockBean



我们在 out 项目中使用 Spring Framework 4.3.14-RELEASE。我们应用程序的结构如下:

parent 
module-one
module-two
...
module-n

现在我们尝试在其中一个模块中编写一些集成测试,我们面临着下一个问题:需要监视 Spring Data JPA 存储库。 在 Spring Boot 中,我们有@SpyBean@MockBean注释,但它们在常规的 Spring 框架中不可用。我们无法迁移到 Spring Boot。

我们曾尝试将spring-boot-testspring-boot-test-starter添加到我们的项目中,但是,很明显,它不起作用:依赖项不会出现在类路径中。

我的问题是:有没有办法在常规项目中使用这些注释?或者也许还有其他方法来监视 Spring Data JPA 存储库?

更新:示例

@Service
public void MegaService {
@Autowired
MegaRepository repository;
// ....
}
public interface MegaRepository extends JpaRepository<MegaModel, Long> {
// ...
}
@Configuration
public class TestRepoConfiguration {
@Bean
MegaRepository megaRepository(MegaRepository repository) {
return Mockito.spy(repository); // of course, it does not work
}
}
@RunWith(SpringJUnit4ClassRunner.class)
public class MegaIntegrationTest {
@Autowired
MegaRepository repository;
public void testMegaLogic() {
when(repository.findAll()).thenAnswer(invocation -> {
System.out.println("Hello, comrades");
return invocation;
});
}
}
您可以使用其中一个
  • 模拟库,如EasyMock,Mockito或Power mock
  • Spring 还提供了一些专门用于模拟的软件包,有关更多详细信息,请参阅链接 https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#mock-objects

最新更新