JUnit Tutorial
Introduction to Junit JUnit Set up JUnit Architecture JUnit Annotations JUnit Fixtures Junit Assertions Junit Categories @Test Annotation Parameters Verification of Exceptions Ignoring tests Time out in JUnit tests Parameterizing tests Test Suite TestWatcher TemporaryFolder ExternalResource Theories in JUnit JUnit Test Runners Execution order of JUnit tests Assumptions in JUnit JUnit and Hamcrest Matchers Running JUnit tests in parallel JUnit and Maven Integration JUnit and Gradle Integration Executing Selenium tests using JUnit test framework Method interceptor and usage JUnit in Intellij IDEA JUnit in EclipseTest watcher rule in junit
TestWatcher rule allows you to log the status of each test as it runs. Notice how we override below methods.- succeeded
- finished
- failed
- skipped
- starting
package rules;
import org.junit.AssumptionViolatedException;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class TestWatcherRule {
@Rule
public TestRule testWatcher = new TestWatcher() {
@Override
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override
protected void succeeded(Description description) {
System.out.println("Test " + description.getDisplayName() + " passed");
}
@Override
protected void failed(Throwable e, Description description) {
System.out.println("Test " + description.getDisplayName() + " failed");
}
@Override
protected void skipped(AssumptionViolatedException e, Description description) {
System.out.println("Test " + description.getDisplayName() + " skipped");
}
@Override
protected void starting(Description description) {
super.starting(description);
System.out.println("Test " + description.getDisplayName() +" Started");
}
@Override
protected void finished(Description description) {
super.finished(description);
System.out.println("Test " + description.getDisplayName() + " finished.");
}
};
@Test
public void simpleMathTest() {
assert 5==3+2;
}
@Test
public void complexMathTest() {
assert Math.sqrt(625)==26;
}
@Test @Ignore
public void stringTest() {
assert "www.softpost.org".length() == 10;
}
}
Here is the output of above code.
Test ignored.Test simpleMathTest(rules.TestWatcherRule) Started
Test simpleMathTest(rules.TestWatcherRule) passed
Test simpleMathTest(rules.TestWatcherRule) finished.
Test complexMathTest(rules.TestWatcherRule) Started
Test complexMathTest(rules.TestWatcherRule) failed
Test complexMathTest(rules.TestWatcherRule) finished.
java.lang.AssertionError
Web development and Automation testing
solutions delivered!!