Best junit code snippet using junit.framework.Interface TestListener.startTest
Source:JUnitTestRunner.java  
...288            }289        }290        Test suite = null;291        Throwable exception = null;292        boolean startTestSuiteSuccess = false;293        try {294            try {295                Class testClass = null;296                if (loader == null) {297                    testClass = Class.forName(junitTest.getName());298                } else {299                    testClass = Class.forName(junitTest.getName(), true,300                                              loader);301                }302                // check for a static suite method first, even when using303                // JUnit 4304                Method suiteMethod = null;305                try {306                    // check if there is a suite method307                    suiteMethod = testClass.getMethod("suite", new Class[0]);308                } catch (NoSuchMethodException e) {309                    // no appropriate suite method found. We don't report any310                    // error here since it might be perfectly normal.311                }312                if (suiteMethod != null) {313                    // if there is a suite method available, then try314                    // to extract the suite from it. If there is an error315                    // here it will be caught below and reported.316                    suite = (Test) suiteMethod.invoke(null, new Class[0]);317                } else {318                    Class junit4TestAdapterClass = null;319                    // Check for JDK 5 first. Will *not* help on JDK 1.4320                    // if only junit-4.0.jar in CP because in that case321                    // linkage of whole task will already have failed! But322                    // will help if CP has junit-3.8.2.jar:junit-4.0.jar.323                    // In that case first C.fN will fail with CNFE and we324                    // will avoid UnsupportedClassVersionError.325                    try {326                        Class.forName("java.lang.annotation.Annotation");327                        if (loader == null) {328                            junit4TestAdapterClass =329                                Class.forName("junit.framework.JUnit4TestAdapter");330                        } else {331                            junit4TestAdapterClass =332                                Class.forName("junit.framework.JUnit4TestAdapter",333                                              true, loader);334                        }335                    } catch (ClassNotFoundException e) {336                        // OK, fall back to JUnit 3.337                    }338                    junit4 = junit4TestAdapterClass != null;339                    if (junit4) {340                        // Let's use it!341                        suite =342                            (Test) junit4TestAdapterClass343                            .getConstructor(new Class[] {Class.class}).344                            newInstance(new Object[] {testClass});345                    } else {346                        // Use JUnit 3.347                        // try to extract a test suite automatically this348                        // will generate warnings if the class is no349                        // suitable Test350                        suite = new TestSuite(testClass);351                    }352                }353            } catch (Throwable e) {354                retCode = ERRORS;355                exception = e;356            }357            long start = System.currentTimeMillis();358            fireStartTestSuite();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.7912     */913    private int[] findJUnit4FailureErrorCount(TestResult res) {914        int failures = 0;915        int errors = 0;916        Enumeration e = res.failures();917        while (e.hasMoreElements()) {918            e.nextElement();...Source:XMLJUnitResultFormatter.java  
...96	}97	/**98	 * The whole testsuite started.99	 */100	public void startTestSuite(JUnitTest suite) {101		doc = getDocumentBuilder().newDocument();102		rootElement = doc.createElement(TESTSUITE);103		rootElement.setAttribute(ATTR_NAME, suite.getName());104		// Output properties105		Element propsElement = doc.createElement(PROPERTIES);106		rootElement.appendChild(propsElement);107		Properties props = suite.getProperties();108		if (props != null) {109			Enumeration e = props.propertyNames();110			while (e.hasMoreElements()) {111				String name = (String) e.nextElement();112				Element propElement = doc.createElement(PROPERTY);113				propElement.setAttribute(ATTR_NAME, name);114				propElement.setAttribute(ATTR_VALUE, props.getProperty(name));115				propsElement.appendChild(propElement);116			}117		}118	}119	/**120	 * The whole testsuite ended.121	 */122	public void endTestSuite(JUnitTest suite) throws BuildException {123		rootElement.setAttribute(ATTR_TESTS, "" + suite.runCount());124		rootElement.setAttribute(ATTR_FAILURES, "" + suite.failureCount());125		rootElement.setAttribute(ATTR_ERRORS, "" + suite.errorCount());126		rootElement.setAttribute(ATTR_TIME, "" + (suite.getRunTime() / 1000.0));127		if (out != null) {128			Writer wri = null;129			try {130				wri = new BufferedWriter(new OutputStreamWriter(out, "UTF8"));131				wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");132				(new DOMElementWriter()).write(rootElement, wri, 0, "  ");133				wri.flush();134			} catch (IOException exc) {135				throw new BuildException("Unable to write log file", exc);136			} finally {137				if (out != System.out && out != System.err) {138					if (wri != null) {139						try {140							wri.close();141						} catch (IOException e) {142							// ignore143						}144					}145				}146			}147		}148	}149	/**150	 * Interface TestListener.151	 * 152	 * <p>153	 * A new Test is started.154	 */155	public void startTest(Test t) {156		testStarts.put(t, new Long(System.currentTimeMillis()));157	}158	/**159	 * Interface TestListener.160	 * 161	 * <p>162	 * A Test is finished.163	 */164	public void endTest(Test test) {165		// Fix for bug #5637 - if a junit.extensions.TestSetup is166		// used and throws an exception during setUp then startTest167		// would never have been called168		if (!testStarts.containsKey(test)) {169			startTest(test);170		}171		Element currentTest = null;172		if (!failedTests.containsKey(test)) {173			currentTest = doc.createElement(TESTCASE);174			currentTest.setAttribute(ATTR_NAME, JUnitVersionHelper175					.getTestCaseName(test));176			// a TestSuite can contain Tests from multiple classes,177			// even tests with the same name - disambiguate them.178			currentTest.setAttribute(ATTR_CLASSNAME, test.getClass().getName());179			rootElement.appendChild(currentTest);180			testElements.put(test, currentTest);181		} else {182			currentTest = (Element) testElements.get(test);183		}...Source:DDTRunMonitor.java  
...182    }183    /**184     * Just let the standard runner do this work - do nothing185     * 186     * @see junit.framework.TestListener#startTest(junit.framework.Test)187     */188    public void startTest(Test test) {189        String method = "";190        this.testRuns = 0;191        this.testErrors = 0;192        this.testFailures = 0;193        if (TestCase.class.isInstance(test)) {194            method = ((TestCase) test).getName();195        }196        log.debug("[" + test.getClass() + "] Start method \"" + method + "\"");197    }198}...Source:MachineMonitor.java  
...78	/*79	 * TestListener interface implementation.80	 */81	@Override82	public void startTest(Test test) {83		SystemTest currentTest = null;84		try {85			if (test instanceof SystemTest) {86				currentTest = (SystemTest) test;87			} else if (test instanceof JSystemJUnit4ClassRunner.TestInfo) {88				currentTest = ((JSystemJUnit4ClassRunner.TestInfo) test).getSystemTest();89			}90			testsReport += getTimeStamp() + "," + currentTest.getClassName() + "." + currentTest.getMethodName() + "\n";91			for (ProcessMonitor process : processMonitors) {92				process.startTest();93			}94		} catch (Exception e) {95			report.report("Unexpected exception: " + e, false);96		}97	}98	@Override99	public void endTest(Test test) {100		for (ProcessMonitor process : processMonitors) {101			try {102				process.endTest();103			} catch (Exception e) {104				report.report("Unexpected exception: " + e, false);105			}106		}...Source:PlainJUnitResultFormatter.java  
...44    }45    /**46     * Empty.47     */48    public void startTestSuite(JUnitTest suite) {49    }50    /**51     * The whole testsuite ended.52     */53    public void endTestSuite(JUnitTest suite) throws BuildException {54        StringBuffer sb = new StringBuffer("Testsuite: ");55        sb.append(suite.getName());56        sb.append(System.getProperty("line.separator"));57        sb.append("Tests run: ");58        sb.append(suite.runCount());59        sb.append(", Failures: ");60        sb.append(suite.failureCount());61        sb.append(", Errors: ");62        sb.append(suite.errorCount());63        sb.append(", Time elapsed: ");64        sb.append(nf.format(suite.getRunTime()/1000.0));65        sb.append(" sec");66        sb.append(System.getProperty("line.separator"));67        sb.append(System.getProperty("line.separator"));68        if (out != null) {69            try {70                out.write(sb.toString().getBytes());71                wri.close();72                out.write(inner.toString().getBytes());73                out.flush();74            } catch (IOException ioex) {75                throw new BuildException("Unable to write output", ioex);76            } finally {77                if (out != System.out && out != System.err) {78                    try {79                        out.close();80                    } catch (IOException e) {}81                }82            }83        }84    }85    /**86     * Interface TestListener.87     *88     * <p>A new Test is started.89     */90    public void startTest(Test t) {91        lastTestStart = System.currentTimeMillis();92        wri.print("Testcase: " + ((TestCase) t).name());93        failed = false;94    }95    /**96     * Interface TestListener.97     *98     * <p>A Test is finished.99     */100    public void endTest(Test test) {101        if (failed) return;102        wri.println(" took " 103                    + nf.format((System.currentTimeMillis()-lastTestStart)104                                / 1000.0)...Source:JUnit3OutcomeListener.java  
...36    public void endTest(Test test) {37        // Nothing.38    }39    @Override40    public void startTest(Test test) {41        // Nothing.42    }43    // OutcomeListener Interface.44    @Override45    public boolean isPass() {46        return mOutcome == Outcome.PASS;47    }48    @Override49    public boolean isFail() {50        return mOutcome == Outcome.FAIL;51    }52    @Override53    public boolean isError() {54        return mOutcome == Outcome.ERROR;...Source:TestListener.java  
...3{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}...startTest
Using AI Code Generation
1import org.junit.runner.notification.RunListener;2import org.junit.runner.Description;3import org.junit.runner.notification.Failure;4import org.junit.runner.Result;5import org.junit.runner.notification.RunNotifier;6import org.junit.runner.JUnitCore;7import org.junit.runner.Request;8import org.junit.runner.Runner;9import org.junit.runner.manipulation.Filter;10import org.junit.runner.manipulation.NoTestsRemainException;11import org.junit.runner.notification.RunListener;12public class TestRunner extends RunListener {13    public static void main(String[] args) {14        JUnitCore core = new JUnitCore();15        core.addListener(new TestRunner());16        core.run(TestSuite.class);17    }18    public void testRunStarted(Description description) throws Exception {19        System.out.println("Number of tests to execute: " + description.testCount());20    }21    public void testRunFinished(Result result) throws Exception {22        System.out.println("Number of tests executed: " + result.getRunCount());23    }24    public void testStarted(Description description) throws Exception {25        System.out.println("Running test: " + description.getMethodName());26    }27    public void testFailure(Failure failure) throws Exception {28        System.out.println("Failed test: " + failure.getDescription().getMethodName());29    }30    public void testFinished(Description description) throws Exception {31        System.out.println("Finished test: " + description.getMethodName());32    }33}34import org.junit.runner.JUnitCore;35import org.junit.runner.Result;36import org.junit.runner.notification.Failure;37public class TestRunner {38    public static void main(String[] args) {39        Result result = JUnitCore.runClasses(TestSuite.class);40        for (Failure failure : result.getFailures()) {41            System.out.println(failure.toString());42        }43        System.out.println(result.wasSuccessful());44    }45}46import org.junit.runner.JUnitCore;47import org.junit.runner.Result;48public class TestRunner {49    public static void main(String[] args) {50        Result result = JUnitCore.runClasses(TestSuite.class);51        System.out.println(result.wasSuccessful());52    }53}54import org.junit.runner.JUnitCore;55public class TestRunner {startTest
Using AI Code Generation
1public class TestListener implements ITestListener {2public void onTestStart(ITestResult result) {3System.out.println("onTestStart -> Test Name: "+result.getName());4}5public void onTestSuccess(ITestResult result) {6System.out.println("onTestSuccess -> Test Name: "+result.getName());7}8public void onTestFailure(ITestResult result) {9System.out.println("onTestFailure -> Test Name: "+result.getName());10}11public void onTestSkipped(ITestResult result) {12System.out.println("onTestSkipped -> Test Name: "+result.getName());13}14public void onTestFailedButWithinSuccessPercentage(ITestResult result) {15System.out.println("onTestFailedButWithinSuccessPercentage -> Test Name: "+result.getName());16}17public void onStart(ITestContext context) {18System.out.println("onStart -> Test Tag Name: "+context.getName());19}20public void onFinish(ITestContext context) {21System.out.println("onFinish -> Test Tag Name: "+context.getName());22}23}24public class Test {25public static void main(String[] args) {26TestListener testListener = new TestListener();27TestResult testResult = new TestResult();28testResult.addListener(testListener);29testResult.startTest(new TestCase("test1"));30testResult.endTest(new TestCase("test1"));31testResult.startTest(new TestCase("test2"));32testResult.endTest(new TestCase("test2"));33testResult.startTest(new TestCase("test3"));34testResult.endTest(new TestCase("test3"));35}36}startTest
Using AI Code Generation
1import junit.framework.*;2public class TestFailure extends TestCase {3    public static Test suite() {4        TestSuite suite = new TestSuite();5        suite.addTest(new TestFailure("testFailure"));6        return suite;7    }8    public TestFailure(String name) { super(name); }9    public void testFailure() { fail(); }10    public static void main(String args[]) {11        TestResult result = new TestResult();12        result.addListener(new TestListener() {13            public void startTest(Test test) {14                System.out.println("Running "+test);15            }16            public void endTest(Test test) {17                System.out.println("Finished "+test);18            }19            public void addError(Test test, Throwable t) {20                System.out.println("Error in "+test+": "+t);21            }22            public void addFailure(Test test, AssertionFailedError t) {23                System.out.println("Failure in "+test+": "+t);24            }25        });26        suite().run(result);27        System.out.println("Number of tests run: "+result.runCount());28        System.out.println("Number of errors: "+result.errorCount());29        System.out.println("Number of failures: "+result.failureCount());30    }31}32Running TestFailure("testFailure")33Finished TestFailure("testFailure")34startTest(Test test)35endTest(Test test)36addError(Test test, Throwable t)37TestResult result = new TestResult();38result.addListener(new TestListener() {39});40TestResult result = new TestResult();41result.removeListener(new TestListener() {42});startTest
Using AI Code Generation
1public class TestListener implements ITestListener {2    public void onTestStart(ITestResult result) {3        System.out.println("Test started: " + result.getName());4    }5    public void onTestSuccess(ITestResult result) {6        System.out.println("Test succeeded: " + result.getName());7    }8    public void onTestFailure(ITestResult result) {9        System.out.println("Test failed: " + result.getName());10    }11    public void onTestSkipped(ITestResult result) {12        System.out.println("Test skipped: " + result.getName());13    }14    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {15        System.out.println("Test failed but within success percentage: " + result.getName());16    }17    public void onStart(ITestContext context) {18        System.out.println("Test started: " + context.getName());19    }20    public void onFinish(ITestContext context) {21        System.out.println("Test finished: " + context.getName());22    }23}24public class TestListener implements ITestListener {25    public void onTestStart(ITestResult result) {26        System.out.println("Test started: " + result.getName());27    }28    public void onTestSuccess(ITestResult result) {29        System.out.println("Test succeeded: " + result.getName());30    }31    public void onTestFailure(ITestResult result) {32        System.out.println("Test failed: " + result.getName());33    }34    public void onTestSkipped(ITestResult result) {35        System.out.println("Test skipped: " + result.getName());36    }37    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {38        System.out.println("Test failed but within success percentage: " + result.getName());39    }40    public void onStart(ITestContext context) {41        System.out.println("Test started: " + context.getName());42    }43    public void onFinish(ITestContext context) {44        System.out.println("Test finished: " + context.getName());45    }46}47public class TestListener implements ITestListener {48    public void onTestStart(ITestResult result) {49        System.out.println("Test started: " + result.getName());50    }startTest
Using AI Code Generation
1public class TestListener implements TestListener {2    public void startTest(Test test) {3    }4}5void addError(Test test, Throwable t)6void addFailure(Test test, AssertionFailedError t)7void endTest(Test test)8void startTest(Test test)9import junit.framework.AssertionFailedError;10import junit.framework.Test;11import junit.framework.TestListener;12public class TestListenerExample implements TestListener {13    public void addError(Test test, Throwable t) {14        System.out.println("TestListenerExample.addError()");15    }16    public void addFailure(Test test, AssertionFailedError t) {17        System.out.println("TestListenerExample.addFailure()");18    }19    public void endTest(Test test) {20        System.out.println("TestListenerExample.endTest()");21    }22    public void startTest(Test test) {23        System.out.println("TestListenerExample.startTest()");24    }25    public static void main(String[] args) {26        TestListenerExample testListenerExample = new TestListenerExample();27        testListenerExample.addError(null, null);28        testListenerExample.addFailure(null, null);29        testListenerExample.endTest(null);30        testListenerExample.startTest(null);31    }32}33TestListenerExample.addError()34TestListenerExample.addFailure()35TestListenerExample.endTest()36TestListenerExample.startTest()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!!
