Skip to content

Instantly share code, notes, and snippets.

@cavoirom
Last active June 15, 2019 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cavoirom/7b2fcf475c50aa37d9e342f4cec8b1d6 to your computer and use it in GitHub Desktop.
Save cavoirom/7b2fcf475c50aa37d9e342f4cec8b1d6 to your computer and use it in GitHub Desktop.
/* 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