下面列出了org.junit.runner.notification.StoppedByUserException#org.junit.runner.notification.Failure 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void logTestRunFinished(Result result) {
Collection<String> lines = MetaList.newArrayList();
lines.add(format("Tests run finished (%d ms)", result.getRunTime()));
lines.add("<> Total tests run: " + result.getRunCount());
lines.add("<> Ignored tests: " + result.getIgnoreCount());
lines.add("<> Failed tests: " + result.getFailureCount());
for (Failure failure : result.getFailures()) {
lines.add("~ " + failure.getTestHeader());
lines.add("[" + failure.getMessage() + "]");
Throwable exception = failure.getException();
lines.add(exception.toString());
for (int i = 0; i <= 5; i += 1) {
StackTraceElement element = exception.getStackTrace()[i];
lines.add(" at " + element.toString());
}
}
//logDebug(logger(), lines);
}
@Override
protected void runChild(FrameworkMethod method, RunNotifier notifier) {
JavaBasedTest javaBasedTest = createJavaBasedTest(method);
WebTauTest webTauTest = javaBasedTest.getTest();
notifier.addListener(new RunListener() {
@Override
public void testFailure(Failure failure) {
webTauTest.setExceptionIfNotSet(failure.getException());
}
});
beforeTestRun(javaBasedTest);
try {
super.runChild(method, notifier);
} catch (Throwable e) {
webTauTest.setExceptionIfNotSet(e);
throw e;
} finally {
afterTestRun(javaBasedTest);
}
}
public static void main(String[] args) {
try {
H2O.main(args);
TestUtil.stall_till_cloudsize(3);
List<Class> tests = JUnitRunner.all();
Result r = org.junit.runner.JUnitCore.runClasses(tests.toArray(new Class[0]));
if( r.getFailureCount() == 0 ) {
System.out.println("Successfully ran the following tests in " + (r.getRunTime() / 1000) + "s");
for( Class c : tests )
System.out.println(c.getName());
} else {
for( Failure f : r.getFailures() ) {
System.err.println(f.getDescription());
if( f.getException() != null )
f.getException().printStackTrace();
}
}
System.exit(r.getFailureCount());
} catch( Throwable t ) {
t.printStackTrace();
System.exit(1);
}
}
@Override
public void testFailure(Failure failure) throws Exception
{
Level level = this.logger.getLevel();
this.logger.setLevel(Level.INFO);
if (TRUE.equals(IS_CDI_TEST_RUNNER_EXECUTION.get()))
{
Description description = failure.getDescription();
this.logger.info("[failed] " + description.getClassName() + "#" + description.getMethodName() +
" message: " + failure.getMessage());
}
try
{
super.testFailure(failure);
}
finally
{
this.logger.setLevel(level);
}
}
@Test(timeout = 500)
public void testThreadDumpAndDeadlocks() throws Exception {
new Deadlock();
String s = null;
while (true) {
s = TimedOutTestsListener.buildDeadlockInfo();
if (s != null) {
break;
}
Thread.sleep(100);
}
Assert.assertEquals(3, countStringOccurrences(s, "BLOCKED"));
Failure failure = new Failure(null, new Exception(TimedOutTestsListener.TEST_TIMED_OUT_PREFIX));
StringWriter writer = new StringWriter();
new TimedOutTestsListener(new PrintWriter(writer)).testFailure(failure);
String out = writer.toString();
Assert.assertTrue(out.contains("THREAD DUMP"));
Assert.assertTrue(out.contains("DEADLOCKS DETECTED"));
System.out.println(out);
}
/**
* This method is called by {@link FortressAntTask} via reflexion and invokes its JUnit tests to verify loaded
* data into LDAP against input data.
*/
@Override
public synchronized void execute( Task task )
{
fortressAntTask = ( FortressAntTask ) task;
fileName = task.getProject().getName();
LOG.info( "execute GroupAntTest JUnit tests on file name: " + fileName );
Result result = JUnitCore.runClasses( GroupAntTest.class );
for ( Failure failure : result.getFailures() )
{
LOG.info( failure.toString() );
}
LOG.info( "TEST SUCCESS: " + result.wasSuccessful() );
}
@Override
public void testFailure(Failure failure) throws Exception {
if (failure != null && failure.getMessage() != null
&& failure.getMessage().startsWith(TEST_TIMED_OUT_PREFIX)) {
output.println("====> TEST TIMED OUT. PRINTING THREAD DUMP. <====");
output.println();
output.print(buildThreadDiagnosticString());
}
}
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
emField.annotate(PersistenceContext.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(JpaUnitException.class));
assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
/**
* Fails the {@link #introspection} test unless we managed to share a compiler.
*/
private void verifyCompilerShared(RunNotifier notifier, int numChildren, int numCompilations) {
System.out.println(String.format(
"Merged %d tests into %d compiler passes",
numChildren,
numCompilations));
int numFilteredChildren = superDescription.get().getChildren().size();
if (numFilteredChildren == numChildren) {
if (numChildren == numCompilations) {
notifier.fireTestFailure(new Failure(
introspection, new AssertionError(MERGE_FAILURE_MESSAGE)));
}
}
}
@org.junit.Test
public void testSuiteFail() {
Result result = run(TestSuiteFail.class);
assertEquals(1, result.getRunCount());
assertEquals(1, result.getFailureCount());
Failure failure = result.getFailures().get(0);
assertEquals("the_failure", failure.getMessage());
assertTrue(failure.getException() instanceof AssertionError);
}
@Override
public void run(final RunNotifier notifier) {
if (!SystemUtils.JAVA_VERSION.startsWith("1.8.")) {
notifier.fireTestAssumptionFailed(new Failure(
Description.createSuiteDescription(clazz),
new IllegalStateException("Java " + SystemUtils.JAVA_VERSION + " not yet supported")));
} else {
super.run(notifier);
}
}
@Override
public void run(final RunReporting<Description, Failure> notifier) {
if (this.ignored) {
notifier.fireTestIgnored(this.description);
return;
}
// apply leaf hooks around the inner block
leafHooks.sorted().runAround(this.description, notifier, block);
}
@Test
public void HavaRunner_will_give_a_helpful_error_message_if_the_test_has_multiple_Scenario_annotations() {
List<Failure> failures = runAndRecordFailures(new HavaRunner(TwoScenarioMethodsTest.class));
assertEquals(
"The class has two tests (one for each scenario). Both should fail because of the two @Scenario methods.",
2,
failures.size()
);
for (Failure failure : failures) {
assertEquals(
"Test com.github.havarunner.scenarios.MultipleScenariosTest$TwoScenarioMethodsTest has more than one @Scenario methods. Remove all but one of them.",
failure.getMessage()
);
}
}
@Override
protected void printFailure(Failure each, String prefix) {
fWriter.println("<span style=\"color: red\">");
fWriter.println(prefix + ") " + each.getTestHeader() + " => " + each.getMessage());
fWriter.println(each.getException());
for (String line : each.getTrace().split("\\r?\\n")) {
if (line.trim().startsWith("at com.openkm")) {
fWriter.println(line);
}
}
fWriter.println("</span>");
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
listener = new OrchestratedInstrumentationListener(this);
listener.odoCallback = mockCallback;
Class<SampleJUnitTest> testClass = SampleJUnitTest.class;
jUnitDescription = Description.createTestDescription(testClass, "sampleTest");
jUnitFailure = new Failure(jUnitDescription, new Throwable("error"));
jUnitResult = new Result();
RunListener jUnitListener = jUnitResult.createListener();
jUnitListener.testRunStarted(jUnitDescription);
jUnitListener.testStarted(jUnitDescription);
jUnitListener.testFinished(jUnitDescription);
}
/**
* Add a test failure.
* @param failure the failure to add.
*/
public void addFailure(final Failure failure) {
final Description d = failure.getDescription();
//CollectionUtils.putInListMap(d.getClassName(), failure, failureMap);
failureMap.putValue(d.getClassName(), failure);
processDescription(d);
failureCount++;
}
@Test
public void shouldNotAppendWhenNullWarnings() throws Exception {
RuntimeException ex = new RuntimeException("foo");
Failure failure = new Failure(Description.EMPTY, ex);
//when
hacker.appendWarnings(failure, null);
//then
assertEquals(ex, failure.getException());
}
/**
* Render the specified failure.
* @param failure the failure to render.
*/
private void renderFailure(final Failure failure) {
renderDescription(failure.getDescription(), "Failure");
if (failure.getException() != null) {
incIndentation();
final String s = ExceptionUtils.getStackTrace(failure.getException());
body.append(indent(s, getIndentation())).append("\n");
decIndentation();
}
}
@Test
public void suiteFailureTest() throws Exception {
Description description = mock(Description.class);
when(description.isTest()).thenReturn(false);
Throwable exception = mock(AssumptionViolatedException.class);
Failure failure = mockFailureWith(exception, description);
doNothing().when(runListener).startFakeTestCase(eq(description));
doNothing().when(runListener).fireTestCaseFailure(eq(exception));
doNothing().when(runListener).finishFakeTestCase();
doNothing().when(runListener).startFakeTestCase(any(Description.class));
runListener.testFailure(failure);
}
@Test
public void HavaRunner_prints_a_helpful_error_message_if_the_scenario_method_is_missing() throws Exception {
final AtomicReference<Failure> expectedFailure = runInvalidScenarioTestMethod();
assertEquals(
"Class InvalidScenarioTest is missing the required constructor. Try adding the following constructor: InvalidScenarioTest(class java.lang.String)",
expectedFailure.get().getMessage()
);
}
@Override
public void run(final RunNotifier notifier) {
if (!SystemUtils.JAVA_VERSION.startsWith("1.8.")) {
notifier.fireTestAssumptionFailed(new Failure(
Description.createSuiteDescription(clazz),
new IllegalStateException("Java " + SystemUtils.JAVA_VERSION + " not yet supported")));
} else {
super.run(notifier);
}
}
/** Mark execution of given {@link Description} as failed. Parent descriptions may be updated accordingly. */
public void executionFailed(Failure failure) {
Description description = failure.getDescription();
allStatuses.put(description, ExecutionStatus.FAILED);
allFailures.put(description, failure);
updateParents(description, ExecutionStatus.FAILED);
}
@Override
public void testFailure(Failure failure) throws Exception {
String testClassName = description.getTestClass() != null ? description.getTestClass().getTypeName() : null;
String testMethodName = description.getMethodName();
String scottReport = FailureRenderer.render(testClassName, testMethodName, failure.getException());
setExceptionMessage(failure.getException(), scottReport);
super.testFailure(failure);
}
/**
* Called when an atomic test fails
*/
@Override
public void testFailure(Failure failure) {
// --- org.apache.commons.lang.EntitiesPerformanceTest::testEscapePrimitive
System.out.println("--- " + failure.getDescription().getClassName() + "::" + failure.getDescription().getMethodName());
System.out.println(failure.getTrace());
}
@Override
public void testAssumptionFailure(final Failure failure) {
try {
doStop();
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
@Override
public void testFailure(Failure failure) {
if (failure.getDescription().isTest()) {
fireTestCaseFailure(failure.getException());
} else {
startFakeTestCase(failure.getDescription());
fireTestCaseFailure(failure.getException());
finishFakeTestCase();
}
}
public void testAssumptionFailure(Failure failure) {
logger.info(">>> testAssumptionFailure called");
Description description = failure.getDescription();
printDescription(description, 1);
// should have been created already in previous call to testStarted
TestSuiteResultsStore store = getStore(description);
store.errors++;
logger.info("<<< testAssumptionFailure called");
}
@Override
public void testFailure(final Failure failure) {
final String uuid = testCases.get();
getLifecycle().updateTestCase(uuid, testResult -> testResult
.setStatus(getStatus(failure.getException()).orElse(null))
.setStatusDetails(getStatusDetails(failure.getException()).orElse(null))
);
}
private void fireTestFailures(List<RunListener> listeners, final List<Failure> failures) {
if (!failures.isEmpty()) {
new SafeNotifier(listeners) {
@Override
protected void notifyListener(RunListener listener) throws Exception {
for (Failure each : failures) {
listener.testFailure(each);
}
}
}.run();
}
}
/**
* Verify super method calls on {@link LuceneTestCase#tearDown()}.
*/
@Test
public void testTeardownChaining() {
Result result = JUnitCore.runClasses(NestedTeardownChain.class);
Assert.assertEquals(1, result.getFailureCount());
Failure failure = result.getFailures().get(0);
Assert.assertTrue(failure.getMessage()
.contains("One of the overrides of tearDown does not propagate the call."));
}