[英]Junit parameterized testing ,a different thought
在这里,我有一个自定义的独立组件,可以接受输入作为jar文件,并从中识别出junit
测试类,并使用下面给出的代码执行它们。
Result result = JUnitCore.runClasses(cls);//cls is Class<?>instance.
我需要的下一步是注入参数(假设输入jar包含基于硒的测试,它需要使用不同的浏览器作为参数),所以我需要从独立组件中将不同的浏览器作为参数注入junit。 这可能吗?
您可以对JUnitCore使用不同的调用,并实现自己的自定义计算机。 如果您的测试类使用自己的注释来注释,则定制计算机可以生成参数化的运行器:
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomParameterized {}
像这样:
@CustomParameterized
public class Example {
private String arg;
public Example(String arg){
this.arg = arg;
}
@org.junit.Test
public void test(){
assertEquals("a",arg);
}
}
JUnitCore调用将变为:
String[] args = new String[]{"a","b"}
Request request = Request.classes(new CustomComputer(args), Example.class);
Result result = new JUnitCore().run(request);
定制计算机如下所示:
public class CustomComputer extends Computer {
private final List<Object> args;
public CustomComputer(String[] args) {
this.args = Arrays.<Object>asList(args);
}
@Override
protected Runner getRunner(RunnerBuilder builder, final Class<?> testClass) throws Throwable {
if (testClass.isAnnotationPresent(Test.CustomParameterized.class)) {
final BlockJUnit4ClassRunnerWithParametersFactory factory = new BlockJUnit4ClassRunnerWithParametersFactory();
return new CustomParameterizedRunner(testClass, factory);
}
return builder.runnerForClass(testClass);
}
private class CustomParameterizedRunner extends Suite {
private final Class<?> testClass;
private final BlockJUnit4ClassRunnerWithParametersFactory factory;
public CustomParameterizedRunner(Class<?> testClass, BlockJUnit4ClassRunnerWithParametersFactory factory) throws InitializationError {
super(testClass, Collections.EMPTY_LIST);
this.testClass = testClass;
this.factory = factory;
}
@Override
protected List<Runner> getChildren() {
List<Runner> runners = new ArrayList<>();
for (Object arg : args) {
runners.add(runnerFor(arg, testClass, factory));
}
return runners;
}
}
private static Runner runnerFor(Object arg, Class<?> testClass, BlockJUnit4ClassRunnerWithParametersFactory factory) {
ArrayList<Object> parameters = new ArrayList<>(1);
parameters.add(arg);
String name = testClass.getSimpleName() + "[" + arg + "]";
TestWithParameters test = new TestWithParameters(name, new TestClass(testClass), parameters);
try {
return factory.createRunnerForTestWithParameters(test);
} catch (InitializationError initializationError) {
throw new RuntimeException(initializationError);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.