下面列出了怎么用org.junit.runners.JUnit4的API类实例代码及写法,或者点击链接到github查看源代码。
public IsolatedTestCaseRunner(final Class<?> testFileClass)
throws InitializationError, ClassNotFoundException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
// Since IsolatedTestCaseRunner runs several isolated tests in a single VM, it
// is good practice to clean resources before each new test.
System.gc();
ClassLoader classLoader = IsolatedTestCaseRunner.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
// When run within e.g. Eclipse, the classloader might not be of instance
// URLClassLoader. In this case, just use the provided class loader which won't
// isolate tests. A set of tests can thus only be run in a single VM from ant
// or maven which pass a URLClassLoader.
classLoader = new IsolatedTestCaseClassLoader((URLClassLoader) classLoader);
}
delegate = new JUnit4(classLoader.loadClass(testFileClass.getName()));
}
@Test
public void test_launch_java_process() throws InterruptedException {
JavaProcess proc = JavaProcess.newBuilder()
.mainClass(Echo.class.getName())
.addClasspath(Echo.class)
.addClasspath(ThreadUtil.class)
.addClasspath(JUnit4.class)
.arguments("one", "two")
.addJvmProp("my.prop", "world")
.addJvmArg("-Xmx512m")
.env("VAR", "Hello")
.pipeStdout()
.pipeStderr()
.recordStdout()
.recordStderr()
.build();
System.out.println(proc.getCommand());
assertEquals(0, proc.waitFor());
assertEquals("Hello\n" +
"world\n" +
"one\n" +
"two\n", proc.getRecordedStdoutText());
assertEquals("", proc.getRecordedStderrText());
}
@Test
public void test_launch_failing_java_process() throws InterruptedException {
JavaProcess proc = JavaProcess.newBuilder()
.mainClass(EchoFail.class.getName())
.addClasspath(EchoFail.class)
.addClasspath(ThreadUtil.class)
.addClasspath(JUnit4.class)
.arguments("one", "two")
.addJvmProp("my.prop", "world")
.addJvmArg("-Xmx512m")
.env("VAR", "Hello")
.recordStdout()
.recordStderr()
.build();
System.out.println(proc.getCommand());
assertEquals(1, proc.waitFor());
assertEquals("Hello\n" +
"world\n" +
"one\n" +
"two\n", proc.getRecordedStdoutText());
assertTrue(proc.getRecordedStderrText().contains("Exception in thread \"main\" java.lang.AssertionError: message"));
}
/**
* @return true if {@param cls} is {@link JUnit4} annotated.
*/
protected boolean isJUnit4TestClass(Class cls) {
// Need to find test classes, otherwise crashes with b/11790448.
if (!cls.getName().endsWith("Test")) {
return false;
}
// Check the annotations.
Annotation annotation = cls.getAnnotation(RunWith.class);
if (annotation != null) {
RunWith runWith = (RunWith) annotation;
Object value = runWith.value();
if (value.equals(JUnit4.class) || value.equals(Suite.class)) {
return true;
}
}
return false;
}
@Test @SuppressWarnings("unchecked")
public void testExceptionsSuppressProperly() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(RepeatedFailure.class));
assertThat(result.getFailureCount(), is(1));
Throwable exception = result.getFailures().get(0).getException();
assertThat(exception, hasMessage(equalTo("Failed: 4")));
assertThat(exception.getSuppressed(), array(hasMessage(equalTo("Failed: 3"))));
assertThat(exception.getSuppressed()[0].getSuppressed(), array(hasMessage(equalTo("Failed: 2"))));
assertThat(exception.getSuppressed()[0].getSuppressed()[0].getSuppressed(), array(hasMessage(equalTo("Failed: 1"))));
}
@Test
public void testNoRetryOnImmediateSuccess() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(ImmediateSuccess.class));
assertTrue(result.wasSuccessful());
assertThat(result.getFailureCount(), is(0));
assertThat(result.getRunCount(), is(1));
}
@Test
public void testRetryAndPassOnEventualSuccess() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(EventualSuccess.class));
assertTrue(result.wasSuccessful());
assertThat(result.getFailureCount(), is(0));
assertThat(result.getRunCount(), is(4));
}
@Test
public void testMissingClassRuleAnnotationTriggersFailure() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(MissingClassRuleAnnotation.class));
assertFalse(result.wasSuccessful());
assertThat(result.getRunCount(), is(0));
assertThat(result.getFailureCount(), is(1));
Throwable throwable = result.getFailures().get(0).getException();
assertThat(throwable, hasMessage(is("TestRetryer must be annotated with both @ClassRule and @Rule")));
}
@Test
public void testMissingRuleAnnotationTriggersFailure() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(MissingRuleAnnotation.class));
assertFalse(result.wasSuccessful());
assertThat(result.getRunCount(), is(1));
assertThat(result.getFailureCount(), is(1));
Throwable throwable = result.getFailures().get(0).getException();
assertThat(throwable, hasMessage(is("TestRetryer must be annotated with both @ClassRule and @Rule")));
}
@Test
public void testEffectivelyEmptyTestIsSafe() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(EffectivelyEmptyTest.class));
assertTrue(result.wasSuccessful());
assertThat(result.getIgnoreCount(), is(1));
assertThat(result.getRunCount(), is(0));
assertThat(result.getFailureCount(), is(0));
}
@Test
public void testFailingTestLogsCorrectly() throws InitializationError {
Result result = new JUnitCore().run(new JUnit4(PartiallyFailingThenPassingTest.class));
assertTrue(result.wasSuccessful());
assertThat(result.getFailureCount(), is(0));
assertThat(result.getRunCount(), is(6));
}
public List<String> findJUnitTests(TestSuite testSuite)
{
List<String> junitTests = new ArrayList<String>();
try {
Class<?>[] clazzez = getUnitTestClasses(testSuite);
if (clazzez != null && clazzez.length > 0) {
for (Class<?> clazz : clazzez) {
//From https://github.com/KentBeck/junit/blob/master/src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java method computeTestMethods
try {
List<FrameworkMethod> methods = new JUnit4(clazz).getTestClass().getAnnotatedMethods(Test.class);
if (methods != null && !methods.isEmpty())
for (FrameworkMethod method: methods)
junitTests.add(clazz.getName() + "/" + method.getName());
}
catch(InitializationError e2) {
StringBuilder errors = new StringBuilder();
for(Throwable cause : e2.getCauses())
errors.append("\n").append(cause.getMessage());
LOG.error("Failed to recognize class '" + clazz + "' as unitTestClass: " + errors.toString());
}
}
}
}
catch(Exception e) {
LOG.error(CLOUD_SECURITY_ERROR + e.getMessage(), e);
}
return junitTests;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Override
protected Class<? extends Runner> getRunnerClass() {
return JUnit4.class;
}
@Test
public void shouldIgnoreJUnitClasses() {
assertIgnored(JUnit4.class);
}