2012-07-03 149 views
52

我想寫一些測試來檢查部署的WAR的XML Spring配置。不幸的是一些bean需要設置一些環境變量或系統屬性。在使用方便的測試樣式和@ContextConfiguration時,如何在spring bean初始化之前設置一個環境變量?如何在春季測試中設置環境變量或系統屬性?

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:whereever/context.xml") 
public class TestWarSpringContext { ... } 

如果我配置具有註釋應用程序上下文,我沒有看到一個鉤在Spring上下文被初始化之前,我可以做一些事情。

回答

75

您可以在靜態初始化初始化系統屬性:Spring應用程序上下文初始化之前

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:whereever/context.xml") 
public class TestWarSpringContext { 

    static { 
     System.setProperty("myproperty", "foo"); 
    } 

} 

靜態初始化代碼會被執行。

+8

愚蠢的我 - 好的,那可行。甚至更好:可能是用於設置系統屬性的'@ BeforeClass'方法和用於刪除它的'@ AfterClass'方法也可以工作,並且很好地清理它自己。 (雖然沒有嘗試過。) –

+1

嘗試了@BeforeClass - 並且它在測試實例中設置其他屬性之前設置系統屬性的工作正常 – wbdarby

+0

感謝您的支持。靜態的東西沒有工作,但與@BeforeClass工作小方法! –

45

從Spring 4.1開始,正確的做法是使用@TestPropertySource註釋。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:whereever/context.xml") 
@TestPropertySource(properties = {"myproperty = foo"}) 
public class TestWarSpringContext { 
    ...  
} 

見@TestPropertySource在Spring docsJavadocs

+1

此註釋還支持屬性文件路徑。 – MigDus

+2

我可以在使用'@TestPropertySource(properties = {「spring.cloud.config.label = feature/branch」})進行測試期間切換Spring Cloud Config Client標籤' –

+0

好的答案,但可悲的是我沒有工作,使用春季4.2.9,房產總是空空如也。只有靜態塊工作...適用於應用程序屬性,但不適用於系統屬性。 – Gregor

4

你也可以使用一個測試ApplicationContextInitializer初始化系統屬性:

public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> 
{ 
    @Override 
    public void initialize(ConfigurableApplicationContext applicationContext) 
    { 
     System.setProperty("myproperty", "value"); 
    } 
} 

,然後除了Spring上下文配置文件的位置上測試類進行配置:

@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class SomeTest 
{ 
... 
} 

這如果應該爲所有的單元測試設置某個系統屬性,則可以避免單向代碼複製。

0

如果你希望你的變量是適用於所有的測試,你可以在你的測試資源目錄中有一個application.properties文件(默認:src/test/resources),這將是這個樣子:

MYPROPERTY=foo 

這一操作將除非您通過@TestPropertySource或類似的方法定義 - 在彈簧文檔章節24. Externalized Configuration中可以找到加載屬性的確切順序。

相關問題