如何用params调用Test class ctor?

时间:2014-11-19 09:35:25

标签: java unit-testing junit junit4

我有单元测试类和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然后运行测试?

1 个答案:

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

}