junit @嵌套类采用默认的application.properties值

bbuxkriu  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(118)

如果我进行集成测试,您能告诉我原因吗:

@TestPropertySource(properties = {"spring.application.environment=dev"})
@SpringBootTest
class IntegrationTest  {

@Autowired
PropertyConfig propertyConfig;

@Nested
@SpringBootTest
@TestPropertySource(properties = {"spring.application.environment=dev", "spring.application.property=example"})
class ServerLoadConfiguration  {

    @Test

    void exampleTest() {
String someProperty = propertyConfig.getSomeProperty(); // old value
        ....
    }
}

例如,测试I从“默认”属性中获取属性值,而不是用@TestPropertySource www.example.com中指定的一个属性覆盖spring.application.property?
如果我在IntegrationTest级别上设置@TestPropertySource(properties = {"spring.application.environment=dev", "spring.application.property=example"}),则嵌套类将应用此值。

e37o9pze

e37o9pze1#

抱歉,无法重现,使用:
1.使用简单(st)快速启动器
1.简单(java〉16)道具:

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("my")
record PropertyConfig(String foo) { }

1.简单(st)配置:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(PropertyConfig.class)
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

}

1.测试:

package com.example.demo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestPropertySource;

@SpringBootTest
@TestPropertySource(properties = {"my.foo=bar"})
public class DemoApplicationIT {

  @Autowired
  private PropertyConfig my;

  @Nested
  class InnerDefaultIT {

    @Autowired
    private PropertyConfig myInner;

    @Test
    void testInner() {
      Assertions.assertNotNull(myInner.foo());
      Assertions.assertEquals(my.foo(), myInner.foo());
    }
  }

  @Nested
  @TestPropertySource(properties = {"my.foo=baz"})
  class InnerIT {

    @Autowired
    private PropertyConfig myInner;

    @Test
    void testInner() {
      Assertions.assertEquals("bar", my.foo());
      Assertions.assertEquals("baz", myInner.foo());
    }
  }

  @Test
  void testOuter() {
    Assertions.assertEquals("bar", my.foo());
  }

}

1.遍数(作为“单元”作为“集成”):

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

相关问题