Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Plain Java */
JUnitCore junit = new JUnitCore();
TestResultListener testResultListener = new TestResultListener();
junit.addListener(testResultListener);
junit.run(testClass);
return testResultListener.getTestResult();
/* Java Reflection */
ClassLoader testClassLoader = testClass.getClassLoader();
Class<Object> junitClass = (Class<Object>) getClass("org.junit.runner.JUnitCore", testClassLoader);
Object junit = junitClass.newInstance();
Class<Object> testResultListenerClass = (Class<Object>) getClass("com.cavoirom.ivy.test.runner.TestResultListener", testClassLoader);
Object testResultListener = testResultListenerClass.newInstance();
junitClass.getMethod("addListener", getClass("org.junit.runner.notification.RunListener", testClassLoader))
.invoke(junit, testResultListener);
junitClass.getMethod("run", Class[].class).invoke(junit, (Object) new Class[] {testClass});
Object testResult = testResultListenerClass.getMethod("getTestResult")
.invoke(testResultListener);
String testResultJson = (String) testResult.getClass().getMethod("toJson").invoke(testResult);
return TestResult.fromJson(testResultJson);
/* Note: the getClass method is a wrapper of Class.forName(...) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment