2015-02-06 135 views
1

作爲後續行動,以Is there any way to conditionally ignore a test with JUnit of Spring?,如果我要被忽略與@IfProfileValue進口同時@IfProfileValue從環境變量設置,測試不執行

@RunWith(SpringJUnit4ClassRunner.class) 
... 

@Resource ConfigurableEnvironment env; 

@Before 
public void env() { 
    log.debug("profiles {} {}", env.getDefaultProfiles(), env.getActiveProfiles()); 
} 

@Test 
@IfProfileValue(name = "integration") 
public void testExecute() throws JobExecutionException 
{...} 

日誌的輸出爲profiles [default] [integration],但testExecute要做到這一點,有什麼當我啓用集成時,我是否錯過了要使此測試運行?我目前通過在IDEA的測試運行器中設置SPRING_PROFILES_ACTIVE=integration來啓用它。

回答

1

首先:您需要使用SpringJUnit4ClassRunner並使用> 4.9的junit版本。

註釋名稱有點直觀:它檢查ProfileValueSource中的鍵值。默認情況下,只有SystemProfileValue源由Spring配置,提供對系統屬性的訪問。

您可以提供自己的ProfileValueSource,用於檢查配置文件是否處於活動狀態並將其配置爲使用ProfileValueSourceConfiguration

如果您的用例是將集成測試分開並且您正在使用Maven,請考慮使用使用故障安全插件並分隔測試,甚至可能在不同的模塊中。

我有一個簡短的例子,由於測試類需要考慮的早期階段,它只能用於系統屬性。既然你說過你使用這個,你可能會對它感到滿意。對於真實情況(CI服務器等),您應該使用更穩健的方法,如故障安全插件和支持單獨集成測試的構建系統。

@RunWith(SpringJUnit4ClassRunner.class) 
@ProfileValueSourceConfiguration(ProfileTest.ProfileProfileValueSource.class) 
@SpringApplicationConfiguration(classes = ProfileTest.class) 
//won't work since not added to system properties! 
//@ActiveProfiles("integration") 
public class ProfileTest 
{ 

@Test 
public void contextLoads() 
{ 
} 

@IfProfileValue(name = "integration", value = "true") 
@Test 
public void runInIntegration() 
{ 
    throw new RuntimeException("in integration"); 
} 

@Test 
public void runDemo() 
{ 
    System.out.println("DEMO, running always"); 
} 

public static class ProfileProfileValueSource implements ProfileValueSource 
{ 
    @Override 
    public String get(String string) 
    { 
     final String systemProfiles = System.getProperty("spring.profiles.active", System.getProperty("SPRING_PROFILES_ACTIVE", "")); 

     final String[] profiles = systemProfiles.split(","); 

     return Arrays.asList(profiles).contains(string) ? "true" : null; 
    } 

} 
} 
+0

我不得不用'... .getEnv(「SPRING_PROFILES_ACTIVE」),因爲物業沒有看到存在/圖還要設置?但除此之外,這個工作。 – xenoterracide 2015-02-15 20:06:15