使用一个 @TestPropertySource 进行多项测试 类

Using one @TestPropertySource for multiple test classes

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

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

我尝试做类似的事情:

@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 {

}

后来在我的 class 测试 class 中使用了 @Import,但我没有成功。

可能吗?

谢谢。

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

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

@Component
public class AnyComponent {

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

    public String getFoo() {
        return foo;
    }

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

家长测试class:

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

测试class:

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

    @Autowired
    private AnyComponent anyComponent;

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

您可以用同样的方式创建其他测试共享 @TestPropertySource

最好的解决方案是在测试 类 之上使用 @Profile@ActiveProfile 注释。将所有测试属性添加到 application-test.yml 文件和

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

使用@ActiveProfile 为该测试执行激活配置文件

TestOne

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

TestTwo

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