PS:编写测试类时,一般是在基类中读取配置文件,并为某些成员赋值。而在MyBuilder中传入基类的成员变量作为过滤条件是不行的,因为MyBuilder的运行还在测试基类之前,此时基类的任何变量都为null。在MyBuilder中自定义过滤条件的变量,必须在MyBuilder中从配置文件里实时读取。由于基类也需要加载配置文件,为避免重复加载,建议将读配置类实现为单例模式:
public class MyConfiguration {
private volatile static MyConfiguration uniqueInstance;
private Properties propertie;
private FileInputStream inputFile;
private MyConfiguration() {
propertie = new Properties();
}
private MyConfiguration(String configFile) {
propertie = new Properties();
try {
inputFile = new FileInputStream(configFile);
propertie.load(inputFile);
inputFile.close();
} catch (FileNotFoundException ex) {
System.out
.println("load properties file failed! maybe file not exist!");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("load properties file failed!");
ex.printStackTrace();
}
}
/**
* @return unique instance
*/
public static MyConfiguration getInstance(String configFile) {
if (uniqueInstance == null) {
synchronized (MyConfiguration.class) {
if (uniqueInstance == null) {
uniqueInstance = new MyConfiguration(configFile);
}
}
}
return uniqueInstance;
}
public String getValue(String key) {
if (propertie.containsKey(key)) {
String value = propertie.getProperty(key);
return value;
} else
return "";
}
}
相应的,MyBuilder可修改为:
public class MyBuilder extends RunnerBuilder {
@Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
String properties = "src/test/resources/test.properties";
MyConfiguration conf = MyConfiguration.getInstance(properties);
if (testClass.getAnnotation(MyIgnore.class) != null) {
if (!"true".equals(conf.getValue("runFlag")))
return new IgnoredClassRunner(testClass);
}
return new BlockJUnit4ClassRunner(testClass);
}
}