【问题标题】:Using one @TestPropertySource for multiple test classes对多个测试类使用一个 @TestPropertySource
【发布时间】:2019-12-03 01:29:04
【问题描述】:

在 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,但我没有让它工作。

有可能吗?

谢谢。

【问题讨论】:

    标签: spring spring-boot spring-test


    【解决方案1】:

    您可以使用 @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

    的其他测试

    【讨论】:

    • 我回家后会试一试,但只是为了添加更多详细信息并将其记录在此处,我认为为了使其正常工作,我需要将属性 inheritProperties 和 inheritLocations 设置为是的。
    【解决方案2】:

    在测试类之上使用@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 {
      }
    

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多