将一个@TestPropertySource用于多个测试类

时间:2019-07-24 20:15:23

标签: spring spring-boot spring-test

在Spring中,可以使用 @TestPropertySource 覆盖某些属性或为带注释的测试类加载特定的属性文件

假设我要执行上述相同的操作,但是我不想在所有测试类中复制并粘贴相同的代码块。是否可以将此配置集中在一个类中?

我试图做类似的事情:

@TestPropertySource(
        properties = {
                "DATABASE_URL: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
                "DATABASE_DDL-AUTO:create-drop"
        },
        locations = {
                "classpath:persistence-${environment}.yml"
                }
)
@Configuration
public class MyConfigurationClass {

}

然后在我的课程测试课中使用 @Import ,但我没有使它起作用。

有可能吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

最好的解决方案是在测试类的顶部使用[531.6MiB/170.74s] Writing /home/schandole/.cache/composer/repo/https---repo.packagist.org/provider-paragonie$constant-time-encoding.json into cache @Profile批注。将所有测试属性添加到@ActiveProfile文件和

使用@Profile 在测试执行期间加载特定的配置文件属性

使用@ActiveProfile 使该配置文件在该测试执行中处于活动状态

TestOne

application-test.yml

TestTwo

  @Profile("test")       // for loading application-test.yml
  @ActiveProfile("test") // for activating test profile
  public class TestOne {
  }

答案 1 :(得分:0)

您可以使用 @TestPropertySource 批注为所有测试创建父类。

具有属性 foo (已经从application.properties或其他属性文件加载)的任何组件类(@Service,..)都可以在JUnit测试中覆盖:

@Component
public class AnyComponent {

    @Value("${foo}")
    private String foo;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }
}

父级测试班:

@TestPropertySource(properties = {"foo:bar"})
public class ParentTest {
}

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class YourTest extends ParentTest {

    @Autowired
    private AnyComponent anyComponent;

    @Test
    public void myTest() {
        System.out.println(anyComponent.getFoo());
    }
}

以相同的方式,您可以创建共享 @TestPropertySource

的其他测试