Annotation Type Rule
Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule. The Statement passed to the TestRule will run any Before methods, then the Test method, and finally any After methods, throwing an exception if any of these fail. If there are multiple annotated Rules on a class, they will be applied in an order that depends on your JVM’s implementation of the reflection API, which is undefined, in general. For example, here is a test class that creates a temporary folder before each test method, and deletes it after each:
Class ErrorCollector
The ErrorCollector rule allows execution of a test to continue after the first problem is found (for example, to collect _all_ the incorrect rows in a table, and report them all at once):
Example 1:
package myWorkjUnit; import junit.framework.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; public class LearnAssertions { /* * The ErrorCollector Rule allows execution of a test to continue after the * first problem is found and report them all at once */ @Rule public ErrorCollector errCol = new ErrorCollector(); @Test public void testAdvertisingPrograms(){ System.out.println("open browser and go to URL"); System.out.println("click on link"); System.out.println("click on one Login link"); String actual = "actual"; String expected = "Expected"; // if("ElementLocation" == "ElementLocation from abve statement"){ // System.out.println("Pass"); // }else{ // System.out.println("fail"); // report Error // } System.out.println("before Assert.assertEquals(expected, actual)"); try { Assert.assertEquals(expected, actual); } catch (Throwable e) { System.out.println("Report Error" + e); errCol.addError(e); } System.out.println("After Assert.assertEquals(expected, actual)"); } }
Example 2: Lets collect more errors ……………
package myWorkjUnit; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; public class UsesErrorCollectorTwice { /* * The ErrorCollector Rule allows execution of a test to continue after the * first problem is found and report them all at once */ @Rule public ErrorCollector collector= new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("first thing went wrong")); collector.addError(new Throwable("second thing went wrong")); // all lines will run, and then a combined failure logged at the end. } }