您的位置:软件测试 > 开源软件测试 > 开源单元测试工具 > junit
自定义注解过滤JUnit测试类
作者:网络转载 发布时间:[ 2013/10/28 15:59:00 ] 推荐标签:

  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);
}
}

上一页123下一页
软件测试工具 | 联系我们 | 投诉建议 | 诚聘英才 | 申请使用列表 | 网站地图
沪ICP备07036474 2003-2017 版权所有 上海泽众软件科技有限公司 Shanghai ZeZhong Software Co.,Ltd