JavaSpringBoot试图使用@JsonTest注释在测试中创建mongo存储库
我有一个使用SpringBoot2和mongodb的应用程序,我正试图通过以下测试来测试一些DTO的json序列化:
@JsonTest
@RunWith(SpringRunner.class)
public class SomeDTOTest {
@Autowired
JacksonTester < SomeDTO > json;
@Test
public void someTest() {}
}
然而,spring正在尝试创建存储库bean,并向我提供以下信息:
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
我有更多的集成测试正在使用存储库,并用@SpringBootTests注释,它们运行良好
有没有办法限制spring只创建JacksonTester bean
# 1 楼答案
我发现在Spring Boot应用程序中既要进行集成测试,又要进行单元测试,这很有挑战性。 我查看了Spring网站,尝试了许多解决方案。对我有效的方法是排除自动配置类:
您可以找到一个完整的Spring启动应用程序,其中包括集成和单元测试here
# 2 楼答案
您可以创建一个没有spring runner的测试
这是一个例子example test
加载spring上下文时,如果有mongotemplate的自动连线注释,spring会尝试提供它。你可以考虑:
在测试中提供了mongo模板
尝试使用@DataMongoTest,它将提供一个嵌入式数据库
不需要设置自动连线
使用@Autowired(required=false)
模拟mongotemplate
使用@MockBean注释来模拟mongoTemplate