本文介紹了Spring-boot,使用不同配置文件的JUnit測(cè)試的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問題描述
我正在嘗試使用JUnit使用application.properties配置文件進(jìn)行集成測(cè)試,以便檢查兩個(gè)不同的平臺(tái)。
我嘗試使用包含兩個(gè)平臺(tái)通用配置的基本配置文件application.properties執(zhí)行此操作,在此基礎(chǔ)上,我為每個(gè)平臺(tái)添加了具有特定平臺(tái)配置的屬性文件application-tensorflow.propertiesapplication-caffe.properties,但我發(fā)現(xiàn)它在JUnit中的工作方式與我在主應(yīng)用程序中使用的方法不同。
我的測(cè)試配置類如下所示:
@Configuration
@PropertySource("classpath:application.properties")
@CompileStatic
@EnableConfigurationProperties
class TestConfig {...}
我使用的是@PropertySource("classpath:application.properties"),所以它會(huì)識(shí)別我的基本配置,我在那里也寫了spring.profiles.active=tensorflow,希望它能識(shí)別TensorFlow應(yīng)用程序配置文件,但是它不會(huì)像在主應(yīng)用程序中那樣從文件/src/test/resources/application-tensorflow.properties或/src/main/resources/application-tensorflow.properties中讀取。
在JUnit測(cè)試中是否有指定彈簧配置文件的特殊方法?實(shí)現(xiàn)我正在嘗試的目標(biāo)的最佳實(shí)踐是什么?
推薦答案
首先:將@ActiveProfiles添加到您的測(cè)試類以定義活動(dòng)配置文件。
此外,您還需要配置應(yīng)加載配置文件。有兩個(gè)選項(xiàng):
在與@ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)的簡(jiǎn)單集成測(cè)試中
在使用@SpringBootTest的完全Spring Boot測(cè)試中
測(cè)試類示例:
@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);
}
}
現(xiàn)在評(píng)估文件src/test/resources/application.properties和src/test/resources/application-test.properties。
這篇關(guān)于Spring-boot,使用不同配置文件的JUnit測(cè)試的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,






