一組應用了junit的測試,需要增加一個動態判斷,來決定是否跑test。我知道這組測試其實已經應用了junit的Category功能,來做測試組的初期分類,在跑這一整套測試的時候,執行環節會針對不同的被測產品給出一個custom參數,測試代碼跑起來後會根據這個custom的值,來選擇排除某些category和包括哪些category。
現在這個策略不夠用了,因爲之前標記好的category,同一個分類下還是有動態選擇執行的需求,於是這次用到了junit中rule特性。
見下面代碼就實現了一個rule。
package com.ibm.robot.web.util;
import com.ibm.robot.web.util.WebPropertiesLoader;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class NotRun5gCase implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
String methodName = description.getMethodName();
loader = new WebPropertiesLoader();
String ap_2g = loader.getString("WIFI.ap.2G", "unknow");
String ap_5g = loader.getString("WIFI.ap.5G", "unknow");
if (!(ap_2G.equals(ap_5G) && methodName.contains("5GHz"))) {
base.evaluate();
}
}
};
}
}
從代碼中可見,這條rule規定當ap_2g的值與ap_5g相等,同時test的方法名中包含5GHz的話,則不執行這個test。
把這條rule應用到具體的test中即可。
public class WiFiTest{
@Rule
public TestRule notRun5gCase = new NotRun5gCase ();
@Before
public void setUp() throws Exception {
System.out.println("setup actions");
}
@After
public void tearDown() throws Exception {
System.out.println("tearDown actions");
}
@Test
public void testWiFi2GHz() {
//to test wi-fi 2g
}
@Test
public void testWiFi5GHz() {
//to test wi-fi 5g
}
}
以上。