我有单元测试类和static main
条目方法。
我知道这是我从main方法运行测试类的方法:
public class SingleJUnitTestRunner {
public static void main(String... args) throws ClassNotFoundException
{
String[] classAndMethod = args[0].split("#");
Request request = Request.method(Class.forName(classAndMethod[0]), classAndMethod[1]);
Result result = new JUnitCore().run(request);
System.exit(result.wasSuccessful() ? 0 : 1);
}
}
有没有办法用params调用测试调用ctor然后运行测试?
答案 0 :(得分:0)
我看了一下Junit源代码并想出了这个:
public static void main(String... args) throws ClassNotFoundException {
String[] classAndMethod = args[0].split("#");
Object[] parameters = new Object[] {"constructor parameter"};
Class<?> className = Class.forName(classAndMethod[0]);
String methodName = classAndMethod[1];
Request request = createRequest(parameters, className, methodName);
Result result = new JUnitCore().run(request);
System.exit(result.wasSuccessful() ? 0 : 1);
}
private static Request createRequest(Object[] parameters, Class<?> className, String methodName) {
Description method = Description.createTestDescription(className, methodName);
return new ConstructorParameterRequest(className, parameters).filterWith(method);
}
自定义Request
类,以便我们可以使用自己的跑步者:
public class ConstructorParameterRequest extends Request {
private Class<?> clazz;
private Object[] parameters;
public ConstructorParameterRequest(Class<?> clazz, Object[] parameters) {
this.clazz = clazz;
this.parameters = parameters;
}
@Override
public Runner getRunner() {
try {
return new ConstructorParameterRunner(clazz, parameters);
} catch (Throwable e) {
return new ErrorReportingRunner(clazz, e);
}
}
}
自定义Runner
类,它使用构造函数参数创建测试类。必须覆盖validateConstructor
,因为BlockJUnit4ClassRunner
检查零参数构造函数:
public class ConstructorParameterRunner extends BlockJUnit4ClassRunner {
private Object[] parameters;
public ConstructorParameterRunner(Class<?> clazz, Object[] parameters) throws InitializationError {
super(clazz);
this.parameters = parameters;
}
@Override
protected void validateConstructor(List<Throwable> errors) {
validateOnlyOneConstructor(errors);
}
@Override
protected Object createTest() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(parameters);
}
}