簡體   English   中英

使用不同的配置文件進行Spring-boot,JUnit測試

[英]Spring-boot, JUnit tests using different profiles

我試圖將application.properties配置文件用於使用JUnit的集成測試,以便檢查兩個不同的平台。

我嘗試使用包含兩個平台的通用配置的基本配置文件application.properties此操作,此外,我還為每個平台添加了具有特定平台配置的屬性文件application-tensorflow.properties application-caffe.properties 。 ,但是我發現它在JUnit中的工作方式不同於我在主應用程序中使用的方式。

我的測試配置類如下所示:

@Configuration
@PropertySource("classpath:application.properties")
@CompileStatic
@EnableConfigurationProperties
class TestConfig {...}

我正在使用@PropertySource("classpath:application.properties")因此它可以識別我的基本配置,我在那里也寫spring.profiles.active=tensorflow ,希望它可以識別tensorflow應用程序配置文件,但不能從文件/src/test/resources/application-tensorflow.properties ,也不從/src/main/resources/application-tensorflow.properties就像在主應用程序中一樣。

有沒有一種特殊的方法可以在JUnit測試中指定彈簧輪廓? 實現我正在嘗試的最佳實踐是什么?

首先:將@ActiveProfiles添加到測試類中以定義活動配置文件。

另外,您需要配置應加載配置文件。 有兩種選擇:

  • 在使用@ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)的簡單集成測試中@ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
  • 使用@SpringBootTest進行完整的Spring Boot測試

示例測試類:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({ "test" })
public class DummyTest {

    @Autowired
    private Environment env;

    @Test
    public void readProps() {
        String value = env.getProperty("prop1") + " " + env.getProperty("prop2");
        assertEquals("Hello World", value);
    }
}

現在,將評估文件src/test/resources/application.propertiessrc/test/resources/application-test.properties

您是否嘗試過用以下方法注釋測試

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = {"tensorflow"})

還要確保application-tensorflow.properties在/ src / test / resources下

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM