首先:您需要使用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;
}
}
}
我不得不用'... .getEnv(「SPRING_PROFILES_ACTIVE」),因爲物業沒有看到存在/圖還要設置?但除此之外,這個工作。 – xenoterracide 2015-02-15 20:06:15