有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (2) 个答案

  1. # 1 楼答案

    我发现在Spring Boot应用程序中既要进行集成测试,又要进行单元测试,这很有挑战性。 我查看了Spring网站,尝试了许多解决方案。对我有效的方法是排除自动配置类:

     @RunWith(SpringRunner.class)
     @JsonTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
     public class JsonTests {
    
          @Autowired
          private JacksonTester json;
    
          @MockBean
          private MyRepository repository;
    
          @MockBean
          private MongoTemplate mongoTemplate;
    
          @Test
          public void someTest() {}
     }      
    

    您可以找到一个完整的Spring启动应用程序,其中包括集成和单元测试here

  2. # 2 楼答案

    您可以创建一个没有spring runner的测试

    这是一个例子example test

    加载spring上下文时,如果有mongotemplate的自动连线注释,spring会尝试提供它。你可以考虑:

    1. 在测试中提供了mongo模板

      尝试使用@DataMongoTest,它将提供一个嵌入式数据库

    2. 不需要设置自动连线

      使用@Autowired(required=false)

    3. 模拟mongotemplate

      使用@MockBean注释来模拟mongoTemplate