Best junit code snippet using org.junit.runner.notification.Failure.getDescription
Source:ReportListener.java
...104 */105 @Override106 public void testFailure(Failure failure) {107 long endTime = System.currentTimeMillis();108 Description description = failure.getDescription();109 Report info = executions.peek(description);110 info.setElapsedTime((endTime - startTime) / 1000d);111 info.setFailure(failure);112 info.setOut(toString(out));113 info.setErr(toString(err));114 }115 /*116 * (non-Javadoc)117 * @see org.junit.runner.notification.RunListener#testAssumptionFailure(org.junit.runner.notification.Failure)118 */119 @Override120 public void testAssumptionFailure(Failure failure) {121 Description description = failure.getDescription();122 Report info = new Report(description);123 info.setElapsedTime(0d);124 info.markAsIgnored();125 info.setMessage(failure.getMessage());126 executions.push(description, info);127 }128 /*129 * (non-Javadoc)130 * @see org.junit.runner.notification.RunListener#testStarted(org.junit.runner.Description)131 */132 @Override133 public void testStarted(Description description) throws Exception {134 startTime = System.currentTimeMillis();135 Report info = new Report(description);136 err = new ByteArrayOutputStream();137 out = new ByteArrayOutputStream();138 System.setErr(new PrintStream(err));139 System.setOut(new PrintStream(out));140 executions.push(description, info);141 if (root == null) {142 root = info;143 }144 }145 /*146 * (non-Javadoc)147 * @see org.junit.runner.notification.RunListener#testFinished(org.junit.runner.Description)148 */149 @Override150 public void testFinished(Description description) throws Exception {151 long endTime = System.currentTimeMillis();152 System.setErr(errBackup);153 System.setOut(outBackup);154 Report info = executions.peek(description);155 info.setElapsedTime((endTime - startTime) / 1000d);156 }157 /*158 * (non-Javadoc)159 * @see org.junit.runner.notification.RunListener#testRunStarted(org.junit.runner.Description)160 */161 @Override162 public void testRunStarted(Description description) throws Exception {163 executions.clear();164 runCount = 0;165 totalTime = 0;166 root = new Report(description.getChildren().get(0));167 executions.push(root.getDescription(), root);168 }169 /*170 * (non-Javadoc)171 * @see org.junit.runner.notification.RunListener#testRunFinished(org.junit.runner.Result)172 */173 @Override174 public void testRunFinished(Result result) throws Exception {175 totalTime = result.getRunTime();176 runCount = result.getRunCount() + result.getIgnoreCount();177 }178 private static String toString(ByteArrayOutputStream out) {179 try {180 return out.toString(UTF_8);181 } catch (UnsupportedEncodingException e) {182 return out.toString();183 }184 }185 /**186 * Returns if the given failure is due {@link AssertionError} or not.187 *188 * @param failure189 * as test result190 * @return {@code true} if the failure is generated by a failed assertion,191 * {@code false} otherwise.192 */193 public static boolean isFailure(Failure failure) {194 return failure != null && failure.getException() instanceof AssertionError;195 }196 /**197 * Returns if the given failure is a general {@link Exception} runtime or198 * not.199 *200 * @param failure201 * as test result202 * @return {@code true} if the failure is raised by an exception,203 * {@code false} otherwise.204 */205 public static boolean isError(Failure failure) {206 return failure != null && !(failure.getException() instanceof AssertionError);207 }208 /**209 * Returns if the last execution of the given test was success or not.210 *211 * @param description212 * of the test213 * @return {@code true} if last execution was success, {@code false}214 * otherwise.215 */216 public boolean wasSuccess(Description description) {217 Report info = executions.peek(description);218 return info == null || info.getFailure() == null;219 }220 /**221 * Gathers all execution test failed.222 *223 * @return an unmodifiable collection of test description.224 */225 public Collection<Description> getFailures() {226 Collection<Description> failures = new LinkedList<Description>();227 for (Description test : executions.keySet()) {228 final Report lastRun = executions.peek(test);229 if (lastRun.getFailure() != null) {230 failures.add(lastRun.getFailure().getDescription());231 }232 }233 return Collections.unmodifiableCollection(failures);234 }235 /**236 * Create a report from all JUnit events.237 * <p>238 * It builds a report that has a map where the key is the test description239 * and the value is an ordered list of all executions result of that test.240 *241 * @return the generated report242 */243 public Report getReport() {244 if (executions.isEmpty()) {245 return new Report(Description.createSuiteDescription("no test execution"));246 }247 Set<Entry<Description,Deque<Report>>> tests = executions.entrySet();248 Map<Description, Report> executionMap = new HashMap<Description, Report>(tests.size());249 for (Entry<Description, Deque<Report>> test : tests) {250 Deque<Report> runs = new ArrayDeque<Report>(test.getValue());251 Report report = null;252 // check if last run was success253 if (runs.peekLast().isSuccess()) {254 report = new Report(runs.pollLast());255 } else {256 // otherwise take the first failure257 report = new Report(runs.poll());258 }259 executionMap.put(test.getKey(), report);260 while (!runs.isEmpty()) {261 report.addRun(new Report(runs.poll()));262 }263 }264 buildExecutionTree(executionMap, root.getDescription());265 Report report = executionMap.get(root.getDescription());266 report.setElapsedTime(totalTime / 1000d);267 report.setRunCount(runCount);268 return report;269 }270 private void buildExecutionTree(Map<Description, Report> executionMap, Description parent) {271 if (!executionMap.containsKey(parent)) {272 // in case of test suite273 executionMap.put(parent, new Report(parent));274 }275 for (Description child : parent.getChildren()) {276 if (!executionMap.containsKey(child)) {277 executionMap.put(child, new Report(child));278 }279 if (executionMap.containsKey(child)) {...
Source:JUnit4RunListener.java
...94 {95 testHeader = "Failure when constructing test";96 }97 ReportEntry report =98 withException( getClassName( failure.getDescription() ), testHeader, createStackTraceWriter( failure ) );99 if ( failure.getException() instanceof AssertionError )100 {101 reporter.testFailed( report );102 }103 else104 {105 reporter.testError( report );106 }107 failureFlag.set( true );108 }109 @SuppressWarnings( { "UnusedDeclaration" } )110 public void testAssumptionFailure( Failure failure )111 {112 reporter.testAssumptionFailure( createReportEntry( failure.getDescription() ) );113 failureFlag.set( true );114 }115 /**116 * Called after a specific test has finished.117 *118 * @see org.junit.runner.notification.RunListener#testFinished(org.junit.runner.Description)119 */120 public void testFinished( Description description )121 throws Exception122 {123 Boolean failure = failureFlag.get();124 if ( failure == null )125 {126 reporter.testSucceeded( createReportEntry( description ) );127 }128 }129 /**130 * Delegates to {@link RunListener#testExecutionSkippedByUser()}.131 */132 public void testExecutionSkippedByUser()133 {134 reporter.testExecutionSkippedByUser();135 }136 private static String getClassName( Description description )137 {138 String name = extractClassName( description );139 if ( name == null || isInsaneJunitNullString( name ) )140 {141 // This can happen upon early failures (class instantiation error etc)142 Description subDescription = description.getChildren().get( 0 );143 if ( subDescription != null )144 {145 name = extractClassName( subDescription );146 }147 if ( name == null )148 {149 name = "Test Instantiation Error";150 }151 }152 return name;153 }154 protected StackTraceWriter createStackTraceWriter( Failure failure )155 {156 return new JUnit4StackTraceWriter( failure );157 }158 protected SimpleReportEntry createReportEntry( Description description )159 {160 return new SimpleReportEntry( getClassName( description ), description.getDisplayName() );161 }162 public static String extractClassName( Description description )163 {164 String displayName = description.getDisplayName();165 Matcher m = PARENS.matcher( displayName );166 return m.find() ? m.group( 1 ) : displayName;167 }168 public static String extractMethodName( Description description )169 {170 String displayName = description.getDisplayName();171 int i = displayName.indexOf( "(" );172 return i >= 0 ? displayName.substring( 0, i ) : displayName;173 }174 public static void rethrowAnyTestMechanismFailures( Result run )175 throws TestSetFailedException176 {177 if ( run.getFailureCount() > 0 )178 {179 for ( Failure failure : run.getFailures() )180 {181 Description description = failure.getDescription();182 if ( JUnit4ProviderUtil.isFailureInsideJUnitItself( description ) )183 {184 final Throwable exception = failure.getException();185 throw new TestSetFailedException( exception );186 }187 }188 }189 }190 private static boolean isInsaneJunitNullString( String value )191 {192 return "null".equals( value );193 }194}...
Source:InstrumentationResultPrinter.java
...50 @Override // org.junit.runner.notification.RunListener51 public void testFailure(Failure failure) throws Exception {52 boolean shouldCallFinish = false;53 if (this.description.equals(Description.EMPTY) && this.testNum == 0 && this.testClass == null) {54 testStarted(failure.getDescription());55 shouldCallFinish = true;56 }57 this.testResultCode = -2;58 reportFailure(failure);59 if (shouldCallFinish) {60 testFinished(failure.getDescription());61 }62 }63 @Override // org.junit.runner.notification.RunListener64 public void testAssumptionFailure(Failure failure) {65 this.testResultCode = -4;66 this.testResult.putString("stack", failure.getTrace());67 }68 private void reportFailure(Failure failure) {69 String trace = failure.getTrace();70 if (trace.length() > MAX_TRACE_SIZE) {71 Log.w("InstrumentationResultPrinter", String.format("Stack trace too long, trimmed to first %s characters.", Integer.valueOf((int) MAX_TRACE_SIZE)));72 trace = String.valueOf(trace.substring(0, MAX_TRACE_SIZE)).concat("\n");73 }74 this.testResult.putString("stack", trace);75 this.testResult.putString("stream", String.format("\nError in %s:\n%s", failure.getDescription().getDisplayName(), failure.getTrace()));76 }77 @Override // org.junit.runner.notification.RunListener78 public void testIgnored(Description description2) throws Exception {79 testStarted(description2);80 this.testResultCode = -3;81 testFinished(description2);82 }83 public void reportProcessCrash(Throwable t) {84 try {85 this.testResultCode = -2;86 Failure failure = new Failure(this.description, t);87 this.testResult.putString("stack", failure.getTrace());88 this.testResult.putString("stream", String.format("\nProcess crashed while executing %s:\n%s", this.description.getDisplayName(), failure.getTrace()));89 testFinished(this.description);...
Source:ResultInnumerator.java
...51 description += failure.getMessage();5253 String body = output.toString();54 body += stackTrace(failure.getException().getStackTrace(),55 failure.getDescription().getClassName() + "." + failure.getDescription().getMethodName());5657 testResults.addTest(description, body, false);58 testFailed = true;5960 }6162 /**63 * Called when a test case is run and fails64 */65 @Override66 public void testFailure(Failure failure) throws Exception {67 super.testFailure(failure);6869 String description = failure.getDescription().toString();7071 Throwable realException = failure.getException();72 if (realException.getCause() != null) {73 realException = realException.getCause();74 }7576 String body = output.toString();77 body += realException.toString();78 body += "\n-----\n";79 body += "Call Stack:\n";80 body += stackTrace(realException.getStackTrace(),81 failure.getDescription().getClassName() + "." + failure.getDescription().getMethodName());8283 testResults.addTest(description, body, false);84 testFailed = true;85 }8687 /**88 * Called when a test case completes, on either success or failure89 */90 @Override91 public void testFinished(Description description) throws Exception {92 super.testFinished(description);9394 if (!testFailed) {95 String body = output.toString();
...
Source:LogRunListener.java
...24 Log.i("TestRunner", valueOf.length() != 0 ? "finished: ".concat(valueOf) : new String("finished: "));25 }26 @Override // org.junit.runner.notification.RunListener27 public void testFailure(Failure failure) throws Exception {28 String valueOf = String.valueOf(failure.getDescription().getDisplayName());29 Log.e("TestRunner", valueOf.length() != 0 ? "failed: ".concat(valueOf) : new String("failed: "));30 Log.e("TestRunner", "----- begin exception -----");31 Log.e("TestRunner", failure.getTrace());32 Log.e("TestRunner", "----- end exception -----");33 }34 @Override // org.junit.runner.notification.RunListener35 public void testAssumptionFailure(Failure failure) {36 String valueOf = String.valueOf(failure.getDescription().getDisplayName());37 Log.e("TestRunner", valueOf.length() != 0 ? "assumption failed: ".concat(valueOf) : new String("assumption failed: "));38 Log.e("TestRunner", "----- begin exception -----");39 Log.e("TestRunner", failure.getTrace());40 Log.e("TestRunner", "----- end exception -----");41 }42 @Override // org.junit.runner.notification.RunListener43 public void testIgnored(Description description) throws Exception {44 String valueOf = String.valueOf(description.getDisplayName());45 Log.i("TestRunner", valueOf.length() != 0 ? "ignored: ".concat(valueOf) : new String("ignored: "));46 }47}...
Source:ExpectedToFailInteractionRunner.java
...14 public ExpectedToFailInteractionRunner(InteractionRunner baseRunner) throws InitializationError {15 this.baseRunner = baseRunner;16 }17 @Override18 public Description getDescription() {19 return baseRunner.getDescription();20 }21 @Override22 public void run(final RunNotifier notifier) {23 RunNotifier testNotifier = new RunNotifier();24 testNotifier.addListener(new RunListener() {25 @Override26 public void testRunStarted(Description description) throws Exception {27 notifier.fireTestRunStarted(description);28 }29 @Override30 public void testRunFinished(Result result) throws Exception {31 notifier.fireTestRunFinished(result);32 }33 @Override34 public void testStarted(Description description) throws Exception {35 notifier.fireTestStarted(description);36 }37 @Override38 public void testFailure(Failure failure) throws Exception {39 notifier.fireTestFinished(failure.getDescription());40 }41 @Override42 public void testIgnored(Description description) throws Exception {43 notifier.fireTestFailure(new Failure(description, new Exception("Expected the test to fail but it did not")));44 }45 @Override46 public void testFinished(Description description) throws Exception {47 notifier.fireTestFailure(new Failure(description, new Exception("Expected the test to fail but it did not")));48 }49 });50 baseRunner.run(testNotifier);51 }52}...
Source:RunUntilFailure.java
...32 public RunUntilFailure(Class<?> c) throws InitializationError {33 this.runner = new BlockJUnit4ClassRunner(c);34 }35 @Override36 public Description getDescription() {37 Description description = Description38 .createSuiteDescription("Run until failure");39 description.addChild(runner.getDescription());40 return description;41 }42 /**43 * Continuously runs the {@link Class class} under test until a failure44 * occurs.45 */46 @Override47 public void run(RunNotifier notifier) {48 class L extends RunListener {49 boolean fail = false;50 @Override51 public void testFailure(Failure failure) throws Exception {52 fail = true;53 }...
Source:SerializableFailure.java
...31 * @param the failure object to be converted32 * @return a SerializableFailure object converted from an org.junit.runner.notification.Failure object33 */34 public static SerializableFailure create(Failure failure) {35 return new SerializableFailure(SerializableDescription.create(failure.getDescription()),failure.getException());36 }37 /**38 * Restore an org.junit.runner.notification.Failure object from this SerializableFailure object.39 * @return the restored org.junit.runner.notification.Failure object40 */41 public Failure restore() {42 return new Failure(description.restore(), thrownException);43 }44}...
getDescription
Using AI Code Generation
1import org.junit.runner.JUnitCore;2import org.junit.runner.Result;3import org.junit.runner.notification.Failure;4public class TestRunner {5 public static void main(String[] args) {6 Result result = JUnitCore.runClasses(TestJunit.class);7 for (Failure failure : result.getFailures()) {8 System.out.println(failure.getDescription());9 }10 System.out.println(result.wasSuccessful());11 }12}13testAdd(org.junit.TestJunit)14testDivideByZero(org.junit.TestJunit)15testMultiply(org.junit.TestJunit)
getDescription
Using AI Code Generation
1import org.junit.runner.JUnitCore;2import org.junit.runner.Result;3import org.junit.runner.notification.Failure;4public class TestRunner {5 public static void main(String[] args) {6 Result result = JUnitCore.runClasses(TestJunit.class);7 for (Failure failure : result.getFailures()) {8 System.out.println(failure.getDescription());9 }10 System.out.println(result.wasSuccessful());11 }12}13Testcase: testAdd(org.TestJunit)14Testcase: testSetup(org.TestJunit)
getDescription
Using AI Code Generation
1public void testFailure() throws Exception {2 Result result = JUnitCore.runClasses(FailureTest.class);3 for (Failure failure : result.getFailures()) {4 System.out.println(failure.getDescription());5 }6}7public void testFailure() throws Exception {8 Result result = JUnitCore.runClasses(FailureTest.class);9 for (Failure failure : result.getFailures()) {10 System.out.println(failure.getDescription().getTestClass());11 }12}13public void testFailure() throws Exception {14 Result result = JUnitCore.runClasses(FailureTest.class);15 for (Failure failure : result.getFailures()) {16 System.out.println(failure.getDescription().getMethodName());17 }18}19public void testFailure() throws Exception {20 Result result = JUnitCore.runClasses(FailureTest.class);21 for (Failure failure : result.getFailures()) {22 System.out.println(failure.getDescription().getDisplayName());23 }24}25public void testFailure() throws Exception {26 Result result = JUnitCore.runClasses(FailureTest.class);27 for (Failure failure : result.getFailures()) {28 System.out.println(failure.getDescription().getClassName());29 }30}31public void testFailure() throws Exception {32 Result result = JUnitCore.runClasses(FailureTest.class);33 for (Failure failure : result.getFailures()) {34 System.out.println(failure.getDescription().getMethodName());35 }36}37public void testFailure() throws Exception {38 Result result = JUnitCore.runClasses(FailureTest.class
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!!