Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringBootTest-如何在测试级别断言上下文而不是加载和更改属性?_Java_Spring_Spring Boot_Junit_Spring Boot Test - Fatal编程技术网

Java SpringBootTest-如何在测试级别断言上下文而不是加载和更改属性?

Java SpringBootTest-如何在测试级别断言上下文而不是加载和更改属性?,java,spring,spring-boot,junit,spring-boot-test,Java,Spring,Spring Boot,Junit,Spring Boot Test,在测试应用程序配置时,我非常依赖@SpringBootTest。应用程序属性可能很复杂,具有默认值和非平凡的验证。例如: prop: ports: 1205,2303,4039 fqdn: ${server.host}:${ports[0]}/${path} @Configuration SomeConfigClass{ @Value{"${ports}:{#collections.emptyList}"} List<Integer> ports; ..

在测试应用程序配置时,我非常依赖
@SpringBootTest
。应用程序属性可能很复杂,具有默认值和非平凡的验证。例如:

prop:
  ports: 1205,2303,4039
  fqdn: ${server.host}:${ports[0]}/${path}

@Configuration
SomeConfigClass{
   @Value{"${ports}:{#collections.emptyList}"}
   List<Integer> ports;

   ...
}
由于测试框架在应用程序上下文之后加载,因此似乎无法测试应用程序上下文是否加载失败。现在我实际编写测试,手动确认它们失败,然后使用
@忽略
进行注释,这样它们就不会丢失

  • 如何在测试方法而不是类级别更改属性

    @SpringBootTest
    是一个类注释,意味着应用程序属性在测试类级别绑定。这导致许多属性集都需要一个测试类,并使测试套件膨胀。例如,我将以如下测试类结束:

    ConfigPropertiesAllValidTest
    ConfigPropertiesNoneSetTest
    ConfigPropertiesSomeValidSomeNotTest
    
    其中每个测试用例只有一个或两个。最好有一个
    configPropertieTest
    类,每个测试都有不同的道具。这可能吗


  • 同样-我希望避免模拟,因为它们不会捕获Spring在运行时执行的非平凡上下文自动配置。

    您可以使用
    @ActiveProfiles
    注释和
    @SpringBootTest
    注释来加载不同配置文件的属性。这是课堂水平,因此仅对问题的案例1有帮助

    @SpringBootTest(classes = {SomeConfigClass.class})
    @ActiveProfiles("badconfigtest")
    public class BadConfigTest{
        ...
    }
    
    然后对错误的配置使用
    应用程序badconfictest.properties


    我认为您不会找到在同一类中的测试方法之间更改属性的方法。您可以使用@DirtiesContext来重新加载应用程序上下文,但我没有看到使用不同属性文件的方法。我想您可以将这些值注入到已经加载属性的配置类中。

    我们最终使用了本文档中描述的
    ApplicationContextRunner


    谢谢-我已经使用了@ActiveProfiles注释,但它并没有太大的区别,因为它仍然迫使我将一组属性绑定到测试类Adam-谢谢你的问题(写得很好)和你自己对问题的回答:)这对我帮助很大。对于搜索有关
    ApplicationContext
    测试信息的人,还有关于
    ApplicationContextRunner
    baeldung.com/spring-boot-context-runner的文章/指南,还有
    AssertableWebApplicationContext
    AssertableReactiveWebApplicationContext
    类可能会有所帮助测试web应用程序上下文时。还值得一提的是,
    ApplicationContextRunner
    2.0.0
    版本的
    spring boot test
    开始提供。
    @SpringBootTest(classes = {SomeConfigClass.class})
    @ActiveProfiles("badconfigtest")
    public class BadConfigTest{
        ...
    }