java - How can I call Test class ctor with params? -
i have unit test class , static main
entry method.
i know how run test class main method:
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); } }
is there way call test-calls ctor params , run tests?
i took @ junit source code , came this:
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); }
custom request
class can use our own runner:
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); } } }
custom runner
class creates test class constructor parameters. validateconstructor
has overriden because blockjunit4classrunner
checks 0 argument constructor:
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); } }
Comments
Post a Comment