Best junit code snippet using junit.framework.Interface TestListener.addError
Source:JUnitTestRunner.java
...359 startTestSuiteSuccess = true;360 if (exception != null) { // had an exception constructing suite361 for (int i = 0; i < formatters.size(); i++) {362 ((TestListener) formatters.elementAt(i))363 .addError(null, exception);364 }365 junitTest.setCounts(1, 0, 1);366 junitTest.setRunTime(0);367 } else {368 try {369 logTestListenerEvent("tests to run: " + suite.countTestCases());370 suite.run(res);371 } finally {372 if (junit4) {373 int[] cnts = findJUnit4FailureErrorCount(res);374 junitTest.setCounts(res.runCount(), cnts[0], cnts[1]);375 } else {376 junitTest.setCounts(res.runCount(), res.failureCount(),377 res.errorCount());378 }379 junitTest.setRunTime(System.currentTimeMillis() - start);380 }381 }382 } finally {383 if (perm != null) {384 perm.restoreSecurityManager();385 }386 if (savedOut != null) {387 System.setOut(savedOut);388 }389 if (savedErr != null) {390 System.setErr(savedErr);391 }392 systemError.close();393 systemError = null;394 systemOut.close();395 systemOut = null;396 if (startTestSuiteSuccess) {397 sendOutAndErr(new String(outStrm.toByteArray()),398 new String(errStrm.toByteArray()));399 }400 }401 fireEndTestSuite();402 if (retCode != SUCCESS || res.errorCount() != 0) {403 retCode = ERRORS;404 } else if (res.failureCount() != 0) {405 retCode = FAILURES;406 }407 }408 /**409 * Returns what System.exit() would return in the standalone version.410 *411 * @return 2 if errors occurred, 1 if tests failed else 0.412 */413 public int getRetCode() {414 return retCode;415 }416 /**417 * Interface TestListener.418 *419 * <p>A new Test is started.420 * @param t the test.421 */422 public void startTest(Test t) {423 String testName = JUnitVersionHelper.getTestCaseName(t);424 logTestListenerEvent("startTest(" + testName + ")");425 }426 /**427 * Interface TestListener.428 *429 * <p>A Test is finished.430 * @param test the test.431 */432 public void endTest(Test test) {433 String testName = JUnitVersionHelper.getTestCaseName(test);434 logTestListenerEvent("endTest(" + testName + ")");435 }436 private void logTestListenerEvent(String msg) {437 PrintStream out = savedOut != null ? savedOut : System.out;438 if (logTestListenerEvents) {439 out.flush();440 out.println(JUnitTask.TESTLISTENER_PREFIX + msg);441 out.flush();442 }443 }444 /**445 * Interface TestListener for JUnit <= 3.4.446 *447 * <p>A Test failed.448 * @param test the test.449 * @param t the exception thrown by the test.450 */451 public void addFailure(Test test, Throwable t) {452 String testName = JUnitVersionHelper.getTestCaseName(test);453 logTestListenerEvent("addFailure(" + testName + ", " + t.getMessage() + ")");454 if (haltOnFailure) {455 res.stop();456 }457 }458 /**459 * Interface TestListener for JUnit > 3.4.460 *461 * <p>A Test failed.462 * @param test the test.463 * @param t the assertion thrown by the test.464 */465 public void addFailure(Test test, AssertionFailedError t) {466 addFailure(test, (Throwable) t);467 }468 /**469 * Interface TestListener.470 *471 * <p>An error occurred while running the test.472 * @param test the test.473 * @param t the error thrown by the test.474 */475 public void addError(Test test, Throwable t) {476 String testName = JUnitVersionHelper.getTestCaseName(test);477 logTestListenerEvent("addError(" + testName + ", " + t.getMessage() + ")");478 if (haltOnError) {479 res.stop();480 }481 }482 /**483 * Permissions for the test run.484 * @since Ant 1.6485 * @param permissions the permissions to use.486 */487 public void setPermissions(Permissions permissions) {488 perm = permissions;489 }490 /**491 * Handle a string destined for standard output.492 * @param output the string to output493 */494 public void handleOutput(String output) {495 if (!logTestListenerEvents && output.startsWith(JUnitTask.TESTLISTENER_PREFIX)) {496 // ignore497 } else if (systemOut != null) {498 systemOut.print(output);499 }500 }501 /**502 * Handle input.503 * @param buffer not used.504 * @param offset not used.505 * @param length not used.506 * @return -1 always.507 * @throws IOException never.508 * @see org.apache.tools.ant.Task#handleInput(byte[], int, int)509 *510 * @since Ant 1.6511 */512 public int handleInput(byte[] buffer, int offset, int length)513 throws IOException {514 return -1;515 }516 /** {@inheritDoc}. */517 public void handleErrorOutput(String output) {518 if (systemError != null) {519 systemError.print(output);520 }521 }522 /** {@inheritDoc}. */523 public void handleFlush(String output) {524 if (systemOut != null) {525 systemOut.print(output);526 }527 }528 /** {@inheritDoc}. */529 public void handleErrorFlush(String output) {530 if (systemError != null) {531 systemError.print(output);532 }533 }534 private void sendOutAndErr(String out, String err) {535 for (int i = 0; i < formatters.size(); i++) {536 JUnitResultFormatter formatter =537 ((JUnitResultFormatter) formatters.elementAt(i));538 formatter.setSystemOutput(out);539 formatter.setSystemError(err);540 }541 }542 private void fireStartTestSuite() {543 for (int i = 0; i < formatters.size(); i++) {544 ((JUnitResultFormatter) formatters.elementAt(i))545 .startTestSuite(junitTest);546 }547 }548 private void fireEndTestSuite() {549 for (int i = 0; i < formatters.size(); i++) {550 ((JUnitResultFormatter) formatters.elementAt(i))551 .endTestSuite(junitTest);552 }553 }554 /**555 * Add a formatter.556 * @param f the formatter to add.557 */558 public void addFormatter(JUnitResultFormatter f) {559 formatters.addElement(f);560 }561 /** {@inheritDoc}. */562 public void addFormatter(JUnitTaskMirror.JUnitResultFormatterMirror f) {563 formatters.addElement((JUnitResultFormatter) f);564 }565 /**566 * Entry point for standalone (forked) mode.567 *568 * Parameters: testcaseclassname plus parameters in the format569 * key=value, none of which is required.570 *571 * <table cols="4" border="1">572 * <tr><th>key</th><th>description</th><th>default value</th></tr>573 *574 * <tr><td>haltOnError</td><td>halt test on575 * errors?</td><td>false</td></tr>576 *577 * <tr><td>haltOnFailure</td><td>halt test on578 * failures?</td><td>false</td></tr>579 *580 * <tr><td>formatter</td><td>A JUnitResultFormatter given as581 * classname,filename. If filename is ommitted, System.out is582 * assumed.</td><td>none</td></tr>583 *584 * <tr><td>showoutput</td><td>send output to System.err/.out as585 * well as to the formatters?</td><td>false</td></tr>586 *587 * <tr><td>logtestlistenerevents</td><td>log TestListener events to588 * System.out.</td><td>false</td></tr>589 *590 * </table>591 * @param args the command line arguments.592 * @throws IOException on error.593 */594 public static void main(String[] args) throws IOException {595 boolean haltError = false;596 boolean haltFail = false;597 boolean stackfilter = true;598 Properties props = new Properties();599 boolean showOut = false;600 boolean outputToFormat = true;601 boolean logTestListenerEvents = false;602 if (args.length == 0) {603 System.err.println("required argument TestClassName missing");604 System.exit(ERRORS);605 }606 if (args[0].startsWith(Constants.TESTSFILE)) {607 multipleTests = true;608 args[0] = args[0].substring(Constants.TESTSFILE.length());609 }610 for (int i = 1; i < args.length; i++) {611 if (args[i].startsWith(Constants.HALT_ON_ERROR)) {612 haltError = Project.toBoolean(args[i].substring(Constants.HALT_ON_ERROR.length()));613 } else if (args[i].startsWith(Constants.HALT_ON_FAILURE)) {614 haltFail = Project.toBoolean(args[i].substring(Constants.HALT_ON_FAILURE.length()));615 } else if (args[i].startsWith(Constants.FILTERTRACE)) {616 stackfilter = Project.toBoolean(args[i].substring(Constants.FILTERTRACE.length()));617 } else if (args[i].startsWith(Constants.CRASHFILE)) {618 crashFile = args[i].substring(Constants.CRASHFILE.length());619 registerTestCase(Constants.BEFORE_FIRST_TEST);620 } else if (args[i].startsWith(Constants.FORMATTER)) {621 try {622 createAndStoreFormatter(args[i].substring(Constants.FORMATTER.length()));623 } catch (BuildException be) {624 System.err.println(be.getMessage());625 System.exit(ERRORS);626 }627 } else if (args[i].startsWith(Constants.PROPSFILE)) {628 FileInputStream in = new FileInputStream(args[i]629 .substring(Constants.PROPSFILE.length()));630 props.load(in);631 in.close();632 } else if (args[i].startsWith(Constants.SHOWOUTPUT)) {633 showOut = Project.toBoolean(args[i].substring(Constants.SHOWOUTPUT.length()));634 } else if (args[i].startsWith(Constants.LOGTESTLISTENEREVENTS)) {635 logTestListenerEvents = Project.toBoolean(636 args[i].substring(Constants.LOGTESTLISTENEREVENTS.length()));637 } else if (args[i].startsWith(Constants.OUTPUT_TO_FORMATTERS)) {638 outputToFormat = Project.toBoolean(639 args[i].substring(Constants.OUTPUT_TO_FORMATTERS.length()));640 }641 }642 // Add/overlay system properties on the properties from the Ant project643 Hashtable p = System.getProperties();644 for (Enumeration e = p.keys(); e.hasMoreElements();) {645 Object key = e.nextElement();646 props.put(key, p.get(key));647 }648 int returnCode = SUCCESS;649 if (multipleTests) {650 try {651 java.io.BufferedReader reader =652 new java.io.BufferedReader(new java.io.FileReader(args[0]));653 String testCaseName;654 int code = 0;655 boolean errorOccurred = false;656 boolean failureOccurred = false;657 String line = null;658 while ((line = reader.readLine()) != null) {659 StringTokenizer st = new StringTokenizer(line, ",");660 testCaseName = st.nextToken();661 JUnitTest t = new JUnitTest(testCaseName);662 t.setTodir(new File(st.nextToken()));663 t.setOutfile(st.nextToken());664 code = launch(t, haltError, stackfilter, haltFail,665 showOut, outputToFormat,666 logTestListenerEvents, props);667 errorOccurred = (code == ERRORS);668 failureOccurred = (code != SUCCESS);669 if (errorOccurred || failureOccurred) {670 if ((errorOccurred && haltError)671 || (failureOccurred && haltFail)) {672 registerNonCrash();673 System.exit(code);674 } else {675 if (code > returnCode) {676 returnCode = code;677 }678 System.out.println("TEST " + t.getName()679 + " FAILED");680 }681 }682 }683 } catch (IOException e) {684 e.printStackTrace();685 }686 } else {687 returnCode = launch(new JUnitTest(args[0]), haltError,688 stackfilter, haltFail,689 showOut, outputToFormat,690 logTestListenerEvents, props);691 }692 registerNonCrash();693 System.exit(returnCode);694 }695 private static Vector fromCmdLine = new Vector();696 private static void transferFormatters(JUnitTestRunner runner,697 JUnitTest test) {698 runner.addFormatter(new JUnitResultFormatter() {699 public void startTestSuite(JUnitTest suite) throws BuildException {700 }701 public void endTestSuite(JUnitTest suite) throws BuildException {702 }703 public void setOutput(OutputStream out) {704 }705 public void setSystemOutput(String out) {706 }707 public void setSystemError(String err) {708 }709 public void addError(Test arg0, Throwable arg1) {710 }711 public void addFailure(Test arg0, AssertionFailedError arg1) {712 }713 public void endTest(Test arg0) {714 }715 public void startTest(Test arg0) {716 registerTestCase(JUnitVersionHelper.getTestCaseName(arg0));717 }718 });719 for (int i = 0; i < fromCmdLine.size(); i++) {720 FormatterElement fe = (FormatterElement) fromCmdLine.elementAt(i);721 if (multipleTests && fe.getUseFile()) {722 File destFile =723 new File(test.getTodir(),724 test.getOutfile() + fe.getExtension());725 fe.setOutfile(destFile);726 }727 runner.addFormatter((JUnitResultFormatter) fe.createFormatter());728 }729 }730 /**731 * Line format is: formatter=<classname>(,<pathname>)?732 */733 private static void createAndStoreFormatter(String line)734 throws BuildException {735 FormatterElement fe = new FormatterElement();736 int pos = line.indexOf(',');737 if (pos == -1) {738 fe.setClassname(line);739 fe.setUseFile(false);740 } else {741 fe.setClassname(line.substring(0, pos));742 fe.setUseFile(true);743 if (!multipleTests) {744 fe.setOutfile(new File(line.substring(pos + 1)));745 } else {746 int fName = line.indexOf(IGNORED_FILE_NAME);747 if (fName > -1) {748 fe.setExtension(line749 .substring(fName750 + IGNORED_FILE_NAME.length()));751 }752 }753 }754 fromCmdLine.addElement(fe);755 }756 /**757 * Returns a filtered stack trace.758 * This is ripped out of junit.runner.BaseTestRunner.759 * @param t the exception to filter.760 * @return the filtered stack trace.761 */762 public static String getFilteredTrace(Throwable t) {763 String trace = StringUtils.getStackTrace(t);764 return JUnitTestRunner.filterStack(trace);765 }766 /**767 * Filters stack frames from internal JUnit and Ant classes768 * @param stack the stack trace to filter.769 * @return the filtered stack.770 */771 public static String filterStack(String stack) {772 if (!filtertrace) {773 return stack;774 }775 StringWriter sw = new StringWriter();776 PrintWriter pw = new PrintWriter(sw);777 StringReader sr = new StringReader(stack);778 BufferedReader br = new BufferedReader(sr);779 String line;780 try {781 while ((line = br.readLine()) != null) {782 if (!filterLine(line)) {783 pw.println(line);784 }785 }786 } catch (Exception e) {787 return stack; // return the stack unfiltered788 }789 return sw.toString();790 }791 private static boolean filterLine(String line) {792 for (int i = 0; i < DEFAULT_TRACE_FILTERS.length; i++) {793 if (line.indexOf(DEFAULT_TRACE_FILTERS[i]) != -1) {794 return true;795 }796 }797 return false;798 }799 /**800 * @since Ant 1.6.2801 */802 private static int launch(JUnitTest t, boolean haltError,803 boolean stackfilter, boolean haltFail,804 boolean showOut, boolean outputToFormat,805 boolean logTestListenerEvents,806 Properties props) {807 t.setProperties(props);808 JUnitTestRunner runner =809 new JUnitTestRunner(t, haltError, stackfilter, haltFail, showOut,810 logTestListenerEvents, null);811 runner.forked = true;812 runner.outputToFormatters = outputToFormat;813 transferFormatters(runner, t);814 runner.run();815 return runner.getRetCode();816 }817 /**818 * @since Ant 1.7819 */820 private static void registerNonCrash()821 throws IOException {822 if (crashFile != null) {823 FileWriter out = null;824 try {825 out = new FileWriter(crashFile);826 out.write(Constants.TERMINATED_SUCCESSFULLY + "\n");827 out.flush();828 } finally {829 if (out != null) {830 out.close();831 }832 }833 }834 }835 private static void registerTestCase(String testCase) {836 if (crashFile != null) {837 try {838 FileWriter out = null;839 try {840 out = new FileWriter(crashFile);841 out.write(testCase + "\n");842 out.flush();843 } finally {844 if (out != null) {845 out.close();846 }847 }848 } catch (IOException e) {849 // ignored.850 }851 }852 }853 /**854 * Modifies a TestListener when running JUnit 4: treats AssertionFailedError855 * as a failure not an error.856 *857 * @since Ant 1.7858 */859 private TestListener wrapListener(final TestListener testListener) {860 return new TestListener() {861 public void addError(Test test, Throwable t) {862 if (junit4 && t instanceof AssertionFailedError) {863 // JUnit 4 does not distinguish between errors and failures864 // even in the JUnit 3 adapter.865 // So we need to help it a bit to retain compatibility for JUnit 3 tests.866 testListener.addFailure(test, (AssertionFailedError) t);867 } else if (junit4 && t.getClass().getName().equals("java.lang.AssertionError")) {868 // Not strictly necessary but probably desirable.869 // JUnit 4-specific test GUIs will show just "failures".870 // But Ant's output shows "failures" vs. "errors".871 // We would prefer to show "failure" for things that logically are.872 try {873 String msg = t.getMessage();874 AssertionFailedError failure = msg != null875 ? new AssertionFailedError(msg) : new AssertionFailedError();876 // To compile on pre-JDK 4 (even though this should always succeed):877 Method initCause = Throwable.class.getMethod(878 "initCause", new Class[] {Throwable.class});879 initCause.invoke(failure, new Object[] {t});880 testListener.addFailure(test, failure);881 } catch (Exception e) {882 // Rats.883 e.printStackTrace(); // should not happen884 testListener.addError(test, t);885 }886 } else {887 testListener.addError(test, t);888 }889 }890 public void addFailure(Test test, AssertionFailedError t) {891 testListener.addFailure(test, t);892 }893 public void addFailure(Test test, Throwable t) { // pre-3.4894 if (t instanceof AssertionFailedError) {895 testListener.addFailure(test, (AssertionFailedError) t);896 } else {897 testListener.addError(test, t);898 }899 }900 public void endTest(Test test) {901 testListener.endTest(test);902 }903 public void startTest(Test test) {904 testListener.startTest(test);905 }906 };907 }908 /**909 * Use instead of TestResult.get{Failure,Error}Count on JUnit 4,910 * since the adapter claims that all failures are errors.911 * @since Ant 1.7...
Source:JUnit3OutcomeListener.java
...24 /** The result of the execution */25 private Outcome mOutcome = Outcome.PASS;26 // TestListener Interface.27 @Override28 public void addError(Test test, Throwable t) {29 mOutcome = Outcome.ERROR;30 }31 @Override32 public void addFailure(Test test, AssertionFailedError t) {33 mOutcome = Outcome.FAIL;34 }35 @Override36 public void endTest(Test test) {37 // Nothing.38 }39 @Override40 public void startTest(Test test) {41 // Nothing.42 }...
Source:1185.java
...17public interface TestListener extends junit.framework.TestListener {18 /**19 * An error occurred.20 */21 public void addError(Test test, TestFailure testFailure);22 /**23 * A failure occurred.24 */25 public void addFailure(Test test, TestFailure testFailure);26}...
Source:1290.java
...17public interface TestListener extends junit.framework.TestListener {18 /**19 * An error occurred.20 */21 public void addError(Test test, TestFailure testFailure);22 /**23 * A failure occurred.24 */25 public void addFailure(Test test, TestFailure testFailure);26}...
Source:TestListener.java
1package junit.framework;2public interface TestListener3{4public abstract void addError(junit.framework.Test test, java.lang.Throwable t);5public abstract void addFailure(junit.framework.Test test, junit.framework.AssertionFailedError t);6public abstract void endTest(junit.framework.Test test);7public abstract void startTest(junit.framework.Test test);8}...
Source:GroupedTestListener.java
...4import junit.framework.TestListener;56public interface GroupedTestListener extends TestListener{7 8 public void addError(Test test, Throwable t, GroupedTestFailure parent);9}
...
addError
Using AI Code Generation
1import junit.framework.Test;2import junit.framework.TestListener;3import junit.framework.TestResult;4public class TestResultListener implements TestListener {5 public void addError(Test test, Throwable t) {6 System.out.println("Test " + test + " threw an error: " + t);7 }8 public void addFailure(Test test, Throwable t) {9 System.out.println("Test " + test + " failed: " + t);10 }11 public void endTest(Test test) {12 System.out.println("Test " + test + " finished");13 }14 public void startTest(Test test) {15 System.out.println("Test " + test + " started");16 }17}18import junit.framework.Test;19import junit.framework.TestResult;20import junit.framework.TestSuite;21public class TestResultDemo {22 public static void main(String[] args) {23 Test test = new TestSuite(TestResultListenerDemo.class);24 TestResult result = new TestResult();25 result.addListener(new TestResultListener());26 test.run(result);27 }28}29import junit.framework.TestCase;30public class TestResultListenerDemo extends TestCase {31 public void testSuccess() {32 assertTrue(true);33 }34 public void testFailure() {35 assertTrue(false);36 }37 public void testError() {38 throw new RuntimeException();39 }40}41junit.framework.TestResult.addListener() method42junit.framework.TestResult.removeListener() method43junit.framework.TestResult.wasSuccessful() method44junit.framework.TestResult.run() method45junit.framework.TestResult.runCount() method46junit.framework.TestResult.failureCount() method
addError
Using AI Code Generation
1import org.junit.runner.Result;2import org.junit.runner.notification.Failure;3import org.junit.runner.notification.RunListener;4public class MyTestListener extends RunListener {5 public void testFailure(Failure failure) throws Exception {6 Result result = failure.getTestHeader();7 result.addError(failure.getException());8 }9}10import org.junit.runner.JUnitCore;11import org.junit.runner.notification.RunListener;12public class TestRunner {13 public static void main(String[] args) {14 JUnitCore junit = new JUnitCore();15 RunListener listener = new MyTestListener();16 junit.addListener(listener);17 junit.run(MyTest.class);18 }19}20Example 2: Using the addFailure() method of the Result class21package com.journaldev.junit;22import org.junit.runner.Result;23import org.junit.runner.notification.Failure;24import org.junit.runner.notification.RunListener;25public class MyTestListener extends RunListener {26 public void testFailure(Failure failure) throws Exception {27 Result result = failure.getTestHeader();28 result.addFailure(failure);29 }30}31Example 3: Using the addFailure() method of the RunListener class32package com.journaldev.junit;33import org.junit.runner.Result;34import org.junit.runner.notification.Failure;35import org.junit.runner.notification.RunListener;36public class MyTestListener extends RunListener {37 public void testFailure(Failure failure) throws Exception {38 failure.getTestHeader().addFailure(failure);39 }40}41Example 4: Using the addFailure() method of the Failure class42package com.journaldev.junit;43import org.junit.runner.Result;44import org.junit.runner.notification.Failure;45import org.junit.runner
addError
Using AI Code Generation
1public class TestListener implements ITestListener {2 public void onTestFailure(ITestResult result) {3 String exceptionMessage = Arrays.toString(result.getThrowable().getStackTrace());4 result.getTestContext().getSuite().getXmlSuite().getTests().get(0).getClasses().get(0).getIncludedMethods().get(0).addParameter("exceptionMessage", exceptionMessage);5 }6}7@Listeners(TestListener.class)8public class SampleTest {9 public void test() {10 throw new RuntimeException("Test failed");11 }12}13public void test() {14 String exceptionMessage = System.getProperty("exceptionMessage");15 if (exceptionMessage != null) {16 Assert.fail(exceptionMessage);17 }18}19@Listeners(TestListener.class)20public class SampleTest {21 public void test() {22 throw new RuntimeException("Test failed");23 }24}25public void test() {26 String exceptionMessage = System.getProperty("exceptionMessage");27 if (exceptionMessage != null) {28 Assert.fail(exceptionMessage);29 }30}31@Listeners(TestListener.class)32public class SampleTest {33 public void test() {34 throw new RuntimeException("Test failed");35 }36}37public void test() {38 String exceptionMessage = System.getProperty("exceptionMessage");39 if (exceptionMessage != null) {40 Assert.fail(exceptionMessage);41 }42}43@Listeners(TestListener.class)44public class SampleTest {45 public void test() {46 throw new RuntimeException("Test failed");47 }48}49public void test() {50 String exceptionMessage = System.getProperty("exceptionMessage");51 if (exceptionMessage != null) {52 Assert.fail(exceptionMessage);53 }54}55@Listeners(TestListener.class)56public class SampleTest {57 public void test() {58 throw new RuntimeException("Test failed");
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!