public static Random RANDOM = new Random(System.nanoTime());
public static final float random(final float pMin, final float pMax) {
return pMin + RANDOM.nextFloat() * (pMax - pMin);
}
Best junit code snippet using org.junit.runner.notification.RunListener
Source: ReportListener.java
...29import org.junit.Ignore;30import org.junit.runner.Description;31import org.junit.runner.Result;32import org.junit.runner.notification.Failure;33import org.junit.runner.notification.RunListener;34/**35 * An implementation {@link RunListener} that gather all JUnit event and create36 * a complete {@link Report}.37 * <p>38 * This listener also deals to wrap standard output and error.39 *40 * @author Nikolas Falco41 */42public class ReportListener extends RunListener {43 public interface DequeValueMap<K, V> extends Map<K, Deque<V>> {44 boolean push(K key, V value);45 V peek(K key);46 }47 @SuppressWarnings("serial")48 private static class DequeValueMapImpl<K, V> extends HashMap<K, Deque<V>> implements DequeValueMap<K, V> {49 @Override50 public boolean push(K key, V value) {51 Deque<V> values = get(key);52 if (values == null) {53 values = new ArrayDeque<V>();54 put(key, values);55 }56 return values.add(value);57 }58 @Override59 public V peek(K key) {60 Deque<V> values = get(key);61 if (values != null) {62 return values.getLast();63 }64 return null;65 }66 }67 private static final String UTF_8 = "UTF-8";68 /**69 * Backup of the {@link System#out} stream.70 */71 private PrintStream outBackup = System.out; // NOSONAR72 /**73 * Backup of the {@link System#err} stream.74 */75 private PrintStream errBackup = System.err; // NOSONAR76 /**77 * The output stream used during the test execution.78 */79 private ByteArrayOutputStream out;80 /**81 * The error stream used during the test execution.82 */83 private ByteArrayOutputStream err;84 private DequeValueMap<Description, Report> executions = new DequeValueMapImpl<Description, Report>();85 private long startTime;86 private long totalTime;87 private int runCount;88 private Report root;89 /*90 * (non-Javadoc)91 * @see org.junit.runner.notification.RunListener#testIgnored(org.junit.runner.Description)92 */93 @Override94 public void testIgnored(Description description) {95 Report info = new Report(description);96 info.setElapsedTime(0d);97 info.markAsIgnored();98 info.setMessage(description.getAnnotation(Ignore.class).value());99 executions.push(description, info);100 }101 /*102 * (non-Javadoc)103 * @see org.junit.runner.notification.RunListener#testFailure(org.junit.runner.notification.Failure)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 /**...
Source: RunNotifier.java
...4import java.util.List;5import java.util.concurrent.CopyOnWriteArrayList;6import org.junit.runner.Description;7import org.junit.runner.Result;8import org.junit.runner.notification.RunListener;9public class RunNotifier {10 private final List<RunListener> listeners = new CopyOnWriteArrayList();11 private volatile boolean pleaseStop = false;12 public void addListener(RunListener listener) {13 if (listener != null) {14 this.listeners.add(wrapIfNotThreadSafe(listener));15 return;16 }17 throw new NullPointerException("Cannot add a null listener");18 }19 public void removeListener(RunListener listener) {20 if (listener != null) {21 this.listeners.remove(wrapIfNotThreadSafe(listener));22 return;23 }24 throw new NullPointerException("Cannot remove a null listener");25 }26 /* access modifiers changed from: package-private */27 public RunListener wrapIfNotThreadSafe(RunListener listener) {28 if (listener.getClass().isAnnotationPresent(RunListener.ThreadSafe.class)) {29 return listener;30 }31 return new SynchronizedRunListener(listener, this);32 }33 private abstract class SafeNotifier {34 private final List<RunListener> currentListeners;35 /* access modifiers changed from: protected */36 public abstract void notifyListener(RunListener runListener) throws Exception;37 SafeNotifier(RunNotifier runNotifier) {38 this(runNotifier.listeners);39 }40 SafeNotifier(List<RunListener> currentListeners2) {41 this.currentListeners = currentListeners2;42 }43 /* access modifiers changed from: package-private */44 public void run() {45 int capacity = this.currentListeners.size();46 ArrayList<RunListener> safeListeners = new ArrayList<>(capacity);47 ArrayList<Failure> failures = new ArrayList<>(capacity);48 for (RunListener listener : this.currentListeners) {49 try {50 notifyListener(listener);51 safeListeners.add(listener);52 } catch (Exception e) {53 failures.add(new Failure(Description.TEST_MECHANISM, e));54 }55 }56 RunNotifier.this.fireTestFailures(safeListeners, failures);57 }58 }59 public void fireTestRunStarted(final Description description) {60 new SafeNotifier() {61 /* class org.junit.runner.notification.RunNotifier.AnonymousClass1 */62 /* access modifiers changed from: protected */63 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier64 public void notifyListener(RunListener each) throws Exception {65 each.testRunStarted(description);66 }67 }.run();68 }69 public void fireTestRunFinished(final Result result) {70 new SafeNotifier() {71 /* class org.junit.runner.notification.RunNotifier.AnonymousClass2 */72 /* access modifiers changed from: protected */73 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier74 public void notifyListener(RunListener each) throws Exception {75 each.testRunFinished(result);76 }77 }.run();78 }79 public void fireTestStarted(final Description description) throws StoppedByUserException {80 if (!this.pleaseStop) {81 new SafeNotifier() {82 /* class org.junit.runner.notification.RunNotifier.AnonymousClass3 */83 /* access modifiers changed from: protected */84 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier85 public void notifyListener(RunListener each) throws Exception {86 each.testStarted(description);87 }88 }.run();89 return;90 }91 throw new StoppedByUserException();92 }93 public void fireTestFailure(Failure failure) {94 fireTestFailures(this.listeners, Arrays.asList(failure));95 }96 /* access modifiers changed from: private */97 /* access modifiers changed from: public */98 private void fireTestFailures(List<RunListener> listeners2, final List<Failure> failures) {99 if (!failures.isEmpty()) {100 new SafeNotifier(listeners2) {101 /* class org.junit.runner.notification.RunNotifier.AnonymousClass4 */102 /* access modifiers changed from: protected */103 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier104 public void notifyListener(RunListener listener) throws Exception {105 for (Failure each : failures) {106 listener.testFailure(each);107 }108 }109 }.run();110 }111 }112 public void fireTestAssumptionFailed(final Failure failure) {113 new SafeNotifier() {114 /* class org.junit.runner.notification.RunNotifier.AnonymousClass5 */115 /* access modifiers changed from: protected */116 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier117 public void notifyListener(RunListener each) throws Exception {118 each.testAssumptionFailure(failure);119 }120 }.run();121 }122 public void fireTestIgnored(final Description description) {123 new SafeNotifier() {124 /* class org.junit.runner.notification.RunNotifier.AnonymousClass6 */125 /* access modifiers changed from: protected */126 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier127 public void notifyListener(RunListener each) throws Exception {128 each.testIgnored(description);129 }130 }.run();131 }132 public void fireTestFinished(final Description description) {133 new SafeNotifier() {134 /* class org.junit.runner.notification.RunNotifier.AnonymousClass7 */135 /* access modifiers changed from: protected */136 @Override // org.junit.runner.notification.RunNotifier.SafeNotifier137 public void notifyListener(RunListener each) throws Exception {138 each.testFinished(description);139 }140 }.run();141 }142 public void pleaseStop() {143 this.pleaseStop = true;144 }145 public void addFirstListener(RunListener listener) {146 if (listener != null) {147 this.listeners.add(0, wrapIfNotThreadSafe(listener));148 return;149 }150 throw new NullPointerException("Cannot add a null listener");151 }152}...
Source: JUnit4WrappedRunNotifier.java
1package edu.tamu.aser.reex;2import org.junit.runner.Description;3import org.junit.runner.Result;4import org.junit.runner.notification.Failure;5import org.junit.runner.notification.RunListener;6import org.junit.runner.notification.RunNotifier;7import org.junit.runner.notification.StoppedByUserException;8public class JUnit4WrappedRunNotifier extends RunNotifier {9 private final RunNotifier notifier;10 private boolean testExpStarted;11 private Description runningTestDescription;12 private Failure testFailure;13 public JUnit4WrappedRunNotifier(RunNotifier notifier) {14 this.notifier = notifier;15 }16 /**17 * Test exploration is starting reset failed status18 */19 public void testExplorationStarted() {20 this.testExpStarted = true;21 this.testFailure = null;22 }23 /**24 * Only fire started event if the exploration is starting25 */26 @Override27 public void fireTestStarted(Description description) throws StoppedByUserException {28 if (this.testExpStarted) {29 this.notifier.fireTestStarted(description);30 this.runningTestDescription = description;31 // No longer starting32 this.testExpStarted = false;33 }34 }35 /**36 * Intercept test failure37 */38 @Override39 public void fireTestAssumptionFailed(Failure failure) {40 this.notifier.fireTestAssumptionFailed(failure);41 this.testFailure = failure;42 }43 /**44 * Intercept test failure45 */46 @Override47 public void fireTestFailure(Failure failure) {48 this.notifier.fireTestFailure(failure);49 this.testFailure = failure;50 }51 52 public void setFailure(Failure failure) {53 this.testFailure = failure;54 }55 /**56 * Return current test's failure status57 * 58 * @return current test's failure status59 */60 public boolean isTestFailed() {61 return this.testFailure != null;62 }63 64 /**65 * Return current test's failure object66 * 67 * @return current test's failure object68 */69 public Failure getFailure() {70 return this.testFailure;71 }72 /**73 * Do not fire test finished event until exploration is finished.74 */75 @Override76 public void fireTestFinished(Description description) {77 // Will be fired when exploration is completed.78 }79 /**80 * Fires the test finished event.81 */82 public void testExplorationFinished() {83 this.notifier.fireTestFinished(this.runningTestDescription);84 }85 /*86 * (non-Javadoc)87 * 88 * @see89 * org.junit.runner.notification.RunNotifier#fireTestIgnored(org.junit.runner90 * .Description)91 */92 @Override93 public void fireTestIgnored(Description description) {94 this.notifier.fireTestIgnored(description);95 }96 /*97 * (non-Javadoc)98 * 99 * @see100 * org.junit.runner.notification.RunNotifier#addFirstListener(org.junit.101 * runner.notification.RunListener)102 */103 @Override104 public void addFirstListener(RunListener listener) {105 this.notifier.addFirstListener(listener);106 }107 /*108 * (non-Javadoc)109 * 110 * @see111 * org.junit.runner.notification.RunNotifier#addListener(org.junit.runner112 * .notification.RunListener)113 */114 @Override115 public void addListener(RunListener listener) {116 this.notifier.addListener(listener);117 }118 /*119 * (non-Javadoc)120 * 121 * @see122 * org.junit.runner.notification.RunNotifier#fireTestRunFinished(org.junit123 * .runner.Result)124 */125 @Override126 public void fireTestRunFinished(Result result) {127 this.notifier.fireTestRunFinished(result);128 }129 /*130 * (non-Javadoc)131 * 132 * @see133 * org.junit.runner.notification.RunNotifier#fireTestRunStarted(org.junit134 * .runner.Description)135 */136 @Override137 public void fireTestRunStarted(Description description) {138 this.notifier.fireTestRunStarted(description);139 }140 /*141 * (non-Javadoc)142 * 143 * @see org.junit.runner.notification.RunNotifier#pleaseStop()144 */145 @Override146 public void pleaseStop() {147 this.notifier.pleaseStop();148 }149 /*150 * (non-Javadoc)151 * 152 * @see153 * org.junit.runner.notification.RunNotifier#removeListener(org.junit.runner154 * .notification.RunListener)155 */156 @Override157 public void removeListener(RunListener listener) {158 this.notifier.removeListener(listener);159 }160}...
Source: DefaultInternalRunnerTest.java
...5package org.mockito.internal.runners;6import org.junit.Test;7import org.junit.runner.Description;8import org.junit.runner.notification.Failure;9import org.junit.runner.notification.RunListener;10import org.junit.runner.notification.RunNotifier;11import org.mockito.Mock;12import org.mockito.internal.junit.MockitoTestListener;13import org.mockito.internal.junit.TestFinishedEvent;14import org.mockito.internal.util.Supplier;15import static org.junit.Assert.assertNotNull;16import static org.junit.Assert.assertTrue;17import static org.mockito.ArgumentMatchers.any;18import static org.mockito.Mockito.*;19public class DefaultInternalRunnerTest {20 private final RunListener runListener = mock(RunListener.class);21 private final MockitoTestListener mockitoTestListener = mock(MockitoTestListener.class);22 private final Supplier<MockitoTestListener> supplier = new Supplier<MockitoTestListener>() {23 public MockitoTestListener get() {24 return mockitoTestListener;25 }26 };27 @Test28 public void does_not_fail_when_tests_succeeds() throws Exception {29 new DefaultInternalRunner(SuccessTest.class, supplier)30 .run(newNotifier(runListener));31 verify(runListener, never()).testFailure(any(Failure.class));32 verify(runListener, times(1)).testFinished(any(Description.class));33 verify(mockitoTestListener, only()).testFinished(any(TestFinishedEvent.class));34 }35 @Test36 public void does_not_fail_second_test_when_first_test_fail() throws Exception {37 new DefaultInternalRunner(TestFailOnInitialization.class, supplier)38 .run(newNotifier(runListener));39 verify(runListener, times(1)).testFailure(any(Failure.class));40 verify(runListener, never()).testFinished(any(Description.class));41 verify(mockitoTestListener, never()).testFinished(any(TestFinishedEvent.class));42 reset(runListener);43 new DefaultInternalRunner(SuccessTest.class, supplier)44 .run(newNotifier(runListener));45 verify(runListener, never()).testFailure(any(Failure.class));46 verify(runListener, times(1)).testFinished(any(Description.class));47 verify(mockitoTestListener, only()).testFinished(any(TestFinishedEvent.class));48 }49 private RunNotifier newNotifier(RunListener listener) {50 RunNotifier notifier = new RunNotifier();51 notifier.addListener(listener);52 return notifier;53 }54 public static final class SuccessTest {55 @Test56 public void test() {57 assertTrue(true);58 }59 }60 public static final class TestFailOnInitialization {61 @Mock62 private System system;63 @Test...
Source: LogRunListener.java
2import android.util.Log;3import org.junit.runner.Description;4import org.junit.runner.Result;5import org.junit.runner.notification.Failure;6import org.junit.runner.notification.RunListener;7public class LogRunListener extends RunListener {8 @Override // org.junit.runner.notification.RunListener9 public void testRunStarted(Description description) throws Exception {10 Log.i("TestRunner", String.format("run started: %d tests", Integer.valueOf(description.testCount())));11 }12 @Override // org.junit.runner.notification.RunListener13 public void testRunFinished(Result result) throws Exception {14 Log.i("TestRunner", String.format("run finished: %d tests, %d failed, %d ignored", Integer.valueOf(result.getRunCount()), Integer.valueOf(result.getFailureCount()), Integer.valueOf(result.getIgnoreCount())));15 }16 @Override // org.junit.runner.notification.RunListener17 public void testStarted(Description description) throws Exception {18 String valueOf = String.valueOf(description.getDisplayName());19 Log.i("TestRunner", valueOf.length() != 0 ? "started: ".concat(valueOf) : new String("started: "));20 }21 @Override // org.junit.runner.notification.RunListener22 public void testFinished(Description description) throws Exception {23 String valueOf = String.valueOf(description.getDisplayName());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: SynchronizedRunListener.java
1package org.junit.runner.notification;2import org.junit.runner.Description;3import org.junit.runner.Result;4import org.junit.runner.notification.RunListener;5/* access modifiers changed from: package-private */6@RunListener.ThreadSafe7public final class SynchronizedRunListener extends RunListener {8 private final RunListener listener;9 private final Object monitor;10 SynchronizedRunListener(RunListener listener2, Object monitor2) {11 this.listener = listener2;12 this.monitor = monitor2;13 }14 @Override // org.junit.runner.notification.RunListener15 public void testRunStarted(Description description) throws Exception {16 synchronized (this.monitor) {17 this.listener.testRunStarted(description);18 }19 }20 @Override // org.junit.runner.notification.RunListener21 public void testRunFinished(Result result) throws Exception {22 synchronized (this.monitor) {23 this.listener.testRunFinished(result);24 }25 }26 @Override // org.junit.runner.notification.RunListener27 public void testStarted(Description description) throws Exception {28 synchronized (this.monitor) {29 this.listener.testStarted(description);30 }31 }32 @Override // org.junit.runner.notification.RunListener33 public void testFinished(Description description) throws Exception {34 synchronized (this.monitor) {35 this.listener.testFinished(description);36 }37 }38 @Override // org.junit.runner.notification.RunListener39 public void testFailure(Failure failure) throws Exception {40 synchronized (this.monitor) {41 this.listener.testFailure(failure);42 }43 }44 @Override // org.junit.runner.notification.RunListener45 public void testAssumptionFailure(Failure failure) {46 synchronized (this.monitor) {47 this.listener.testAssumptionFailure(failure);48 }49 }50 @Override // org.junit.runner.notification.RunListener51 public void testIgnored(Description description) throws Exception {52 synchronized (this.monitor) {53 this.listener.testIgnored(description);54 }55 }56 public int hashCode() {57 return this.listener.hashCode();58 }59 public boolean equals(Object other) {60 if (this == other) {61 return true;62 }63 if (!(other instanceof SynchronizedRunListener)) {64 return false;65 }66 return this.listener.equals(((SynchronizedRunListener) other).listener);67 }68 public String toString() {69 return this.listener.toString() + " (with synchronization wrapper)";70 }71}...
Source: JUnitListener.java
...4import org.apache.commons.logging.LogFactory;5import org.junit.runner.Description;6import org.junit.runner.Result;7import org.junit.runner.notification.Failure;8import org.junit.runner.notification.RunListener;9/**10 * @author Jerry Maine - jerry@pramari.com11 *12 */13public class JUnitListener extends RunListener {14 private static final Log logger = LogFactory.getLog(JUnitListener.class);15 16 /* (non-Javadoc)17 * @see org.junit.runner.notification.RunListener#testFinished(org.junit.runner.Description)18 */19 public void testFinished(Description description){20 logger.info("JUnit Finished: " + description);21 }22 23 /* (non-Javadoc)24 * @see org.junit.runner.notification.RunListener#testFailure(org.junit.runner.notification.Failure)25 */26 public void testFailure(Failure failure){27 logger.fatal("JUnit Failure: " + failure);28 //logger.error(failure.getMessage());29 logger.fatal("JUnit Failure: " + failure.getTrace());30 }31 32 /* (non-Javadoc)33 * @see org.junit.runner.notification.RunListener#testRunFinished(org.junit.runner.Result)34 */35 public void testRunFinished(Result result) {36 logger.info("JUnits that ran: " + result.getRunCount());37 logger.info("JUnit runtime: " + ((double) result.getRunTime() / 1000) + " second(s)") ;38 39 if (result.wasSuccessful()) {40 logger.info("No Junits failed.");41 } else {42 logger.fatal("JUnits that failed: " + result.getFailureCount());43 List<Failure> failures = result.getFailures();44 for (Failure failure: failures){45 logger.fatal("JUnit Failure: " + failure);46 //logger.error("JUnit Failure (Stack Trace): " + failure.getTrace());47 }48 }49 }50 51 /* (non-Javadoc)52 * @see org.junit.runner.notification.RunListener#testRunStarted(org.junit.runner.Description)53 */54 public void testRunStarted(Description description) {55 for (Description d: description.getChildren()){56 logger.info("Setting up to run Junit: " + d);57 }58 }59 60 /* (non-Javadoc)61 * @see org.junit.runner.notification.RunListener#testStarted(org.junit.runner.Description)62 */63 public void testStarted(Description description) {64 logger.info("Attempting to run Junit: " + description);65 }66}...
Source: TryJunit.java
...12import org.junit.runner.Description;13import org.junit.runner.JUnitCore;14import org.junit.runner.Result;15import org.junit.runner.notification.Failure;16import org.junit.runner.notification.RunListener;1718import sav.commons.testdata.simplePrograms.org.SimpleProgramTests;1920/**21 * @author LLT22 *23 */24public class TryJunit {2526 @Test27 public void runTest() {28 JUnitCore core = new JUnitCore();29 core.addListener(new RunListener() {30 31 /* (non-Javadoc)32 * @see org.junit.runner.notification.RunListener#testStarted(org.junit.runner.Description)33 */34 @Override35 public void testStarted(Description description) throws Exception {36 super.testStarted(description);37 }38 39 @Override40 public void testRunFinished(Result result) throws Exception {41 System.out.println("on runFinished");42 super.testRunFinished(result);43 }44 45 /* (non-Javadoc)46 * @see org.junit.runner.notification.RunListener#testFailure(org.junit.runner.notification.Failure)47 */48 @Override49 public void testFailure(Failure failure) throws Exception {50 System.out.println("on testFailure!!");51 super.testFailure(failure);52 }53 });54 55 core.run(SimpleProgramTests.class);56 }57}
...
RunListener
Using AI Code Generation
1import org.junit.runner.notification.RunListener;2import org.junit.runner.Description;3import org.junit.runner.Result;4public class TestRunListener extends RunListener {5 public void testRunStarted(Description description) throws Exception {6 System.out.println("Number of test cases to execute: " + description.testCount());7 }8 public void testRunFinished(Result result) throws Exception {9 System.out.println("Number of test cases executed: " + result.getRunCount());10 }11 public void testStarted(Description description) throws Exception {12 System.out.println("Started execution of test case: " + description.getMethodName());13 }14 public void testFinished(Description description) throws Exception {15 System.out.println("Finished execution of test case: " + description.getMethodName());16 }17 public void testFailure(Failure failure) throws Exception {18 System.out.println("Execution of test case failed: " + failure.getDescription().getMethodName());19 }20 public void testIgnored(Description description) throws Exception {21 System.out.println("Execution of test case ignored: " + description.getMethodName());22 }23}24import org.junit.runner.notification.RunNotifier;25import org.junit.runner.notification.Failure;26import org.junit.runner.Description;27import org.junit.runner.Result;28public class TestRunNotifier {29 public static void main(String[] args) {30 RunNotifier notifier = new RunNotifier();31 notifier.addListener(new TestRunListener());32 Description description = Description.createTestDescription(TestRunNotifier.class, "testRunNotifier");33 notifier.fireTestRunStarted(description);34 notifier.fireTestStarted(description);35 notifier.fireTestFailure(new Failure(description, new Exception()));36 notifier.fireTestFinished(description);37 notifier.fireTestRunFinished(new Result());38 }39}
RunListener
Using AI Code Generation
1import org.junit.runner.notification.RunListener;2import org.junit.runner.Description;3import org.junit.runner.Result;4public class RunListenerTest extends RunListener {5 public void testRunStarted(Description description) throws Exception {6 System.out.println("Number of tests to execute: " + description.testCount());7 }8 public void testRunFinished(Result result) throws Exception {9 System.out.println("Number of tests executed: " + result.getRunCount());10 }11 public void testStarted(Description description) throws Exception {12 System.out.println("Starting execution of test case: " + description.getMethodName());13 }14 public void testFinished(Description description) throws Exception {15 System.out.println("Finished execution of test case: " + description.getMethodName());16 }17 public void testFailure(org.junit.runner.notification.Failure failure) throws Exception {18 System.out.println("Test case failed: " + failure.getDescription().getMethodName());19 }20 public void testIgnored(Description description) throws Exception {21 System.out.println("Test case ignored: " + description.getMethodName());22 }23}24import org.junit.runner.JUnitCore;25import org.junit.runner.Result;26import org.junit.runner.notification.Failure;27import org.junit.runner.RunWith;28import org.junit.runners.Suite;29@RunWith(Suite.class)30@Suite.SuiteClasses({31})32public class TestSuite {33 public static void main(String[] args) {34 Result result = JUnitCore.runClasses(TestSuite.class);35 for (Failure failure
RunListener
Using AI Code Generation
1import org.junit.runner.notification.RunListener2import org.junit.runner.Description3import org.junit.runner.Result4class CustomListener extends RunListener {5 def testStarted(Description description) {6 println "Test Started: ${description.methodName}"7 }8 def testFinished(Description description) {9 println "Test Finished: ${description.methodName}"10 }11 def testFailure(Failure failure) {12 println "Test Failed: ${failure.description.methodName}"13 }14 def testIgnored(Description description) {15 println "Test Ignored: ${description.methodName}"16 }17 def testRunFinished(Result result) {18 }19 def testRunStarted(Description description) {20 }21}22import org.junit.runner.RunWith23import org.junit.runner.notification.RunListener24import org.junit.runner.Description25import org.junit.runner.Result26@RunWith(org.junit.runner.RunWith)27class CustomListener extends RunListener {28 def testStarted(Description description) {29 println "Test Started: ${description.methodName}"30 }31 def testFinished(Description description) {32 println "Test Finished: ${description.methodName}"33 }34 def testFailure(Failure failure) {35 println "Test Failed: ${failure.description.methodName}"36 }37 def testIgnored(Description description) {38 println "Test Ignored: ${description.methodName}"39 }40 def testRunFinished(Result result) {41 }42 def testRunStarted(Description description) {43 }44}45import org.junit.runner.RunWith46import org.junit.runner.notification.RunListener47import org.junit.runner.Description48import org.junit.runner.Result49@RunWith(org.junit.runner.RunWith)50class CustomListener extends RunListener {51 def testStarted(Description description) {52 println "Test Started: ${description.methodName}"53 }54 def testFinished(Description description) {55 println "Test Finished: ${description
1public static Random RANDOM = new Random(System.nanoTime());23public static final float random(final float pMin, final float pMax) {4 return pMin + RANDOM.nextFloat() * (pMax - pMin);5}6
Source: Cleanup after all junit tests
1import java.util.Random;23/** Generate random integers in a certain range. */4public final class RandomRange {56 public static final void main(String... aArgs){7 log("Generating random integers in the range 1..10.");89 int START = 1;10 int END = 10;11 Random random = new Random();12 for (int idx = 1; idx <= 10; ++idx){13 showRandomInteger(START, END, random);14 }1516 log("Done.");17 }1819 private static void showRandomInteger(int aStart, int aEnd, Random aRandom){20 if ( aStart > aEnd ) {21 throw new IllegalArgumentException("Start cannot exceed End.");22 }23 //get the range, casting to long to avoid overflow problems24 long range = (long)aEnd - (long)aStart + 1;25 // compute a fraction of the range, 0 <= frac < range26 long fraction = (long)(range * aRandom.nextDouble());27 int randomNumber = (int)(fraction + aStart); 28 log("Generated : " + randomNumber);29 }3031 private static void log(String aMessage){32 System.out.println(aMessage);33 }34} 35
1RandomUtils random = new RandomUtils();2random.nextInt(0, 0); // returns 03random.nextInt(10, 10); // returns 104random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)5random.nextInt(10, -10); // throws assert6
JUnit 4 Expected Exception type
java: how to mock Calendar.getInstance()?
Changing names of parameterized tests
Mocking a class vs. mocking its interface
jUnit ignore @Test methods from base class
Important frameworks/tools to learn
Unit testing a Java Servlet
Meaning of delta or epsilon argument of assertEquals for double values
Different teardown for each @Test in jUnit
Best way to automagically migrate tests from JUnit 3 to JUnit 4?
There's actually an alternative to the @Test(expected=Xyz.class)
in JUnit 4.7 using Rule
and ExpectedException
In your test case you declare an ExpectedException
annotated with @Rule
, and assign it a default value of ExpectedException.none()
. Then in your test that expects an exception you replace the value with the actual expected value. The advantage of this is that without using the ugly try/catch method, you can further specify what the message within the exception was
@Rule public ExpectedException thrown= ExpectedException.none();
@Test
public void myTest() {
thrown.expect( Exception.class );
thrown.expectMessage("Init Gold must be >= 0");
rodgers = new Pirate("Dread Pirate Rodgers" , -100);
}
Using this method, you might be able to test for the message in the generic exception to be something specific.
ADDITION
Another advantage of using ExpectedException
is that you can more precisely scope the exception within the context of the test case. If you are only using @Test(expected=Xyz.class)
annotation on the test, then the Xyz exception can be thrown anywhere in the test code -- including any test setup or pre-asserts within the test method. This can lead to a false positive.
Using ExpectedException, you can defer specifying the thrown.expect(Xyz.class)
until after any setup and pre-asserts, just prior to actually invoking the method under test. Thus, you more accurately scope the exception to be thrown by the actual method invocation rather than any of the test fixture itself.
JUnit 5 NOTE:
JUnit 5 JUnit Jupiter has removed @Test(expected=...)
, @Rule
and ExpectedException
altogether. They are replaced with the new assertThrows()
, which requires the use of Java 8 and lambda syntax. ExpectedException
is still available for use in JUnit 5 through JUnit Vintage. Also JUnit Jupiter will also continue to support JUnit 4 ExpectedException
through use of the junit-jupiter-migrationsupport module, but only if you add an additional class-level annotation of @EnableRuleMigrationSupport
.
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium NUnit Tutorial.
There are various CI/CD tools such as CircleCI, TeamCity, Bamboo, Jenkins, GitLab, Travis CI, GoCD, etc., that help companies streamline their development process and ensure high-quality applications. If we talk about the top CI/CD tools in the market, Jenkins is still one of the most popular, stable, and widely used open-source CI/CD tools for building and automating continuous integration, delivery, and deployment pipelines smoothly and effortlessly.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium pytest Tutorial.
The Selenium automation framework supports many programming languages such as Python, PHP, Perl, Java, C#, and Ruby. But if you are looking for a server-side programming language for automation testing, Selenium WebDriver with PHP is the ideal combination.
While working on a project for test automation, you’d require all the Selenium dependencies associated with it. Usually these dependencies are downloaded and upgraded manually throughout the project lifecycle, but as the project gets bigger, managing dependencies can be quite challenging. This is why you need build automation tools such as Maven to handle them automatically.
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!!