JUnit Error Collector

While writing a test script, you want to execute all the tests even if any line of code fails due to network failure, assertion failure, or any other reason. In that situation, you can still continue executing test script using a special feature provided by JUnit known as “error collector.”

For this, JUnit uses @Rule annotation which is used to create an object of error collector. Once the object for error collector is created, you can easily add all the errors into the object using method addError (Throwable error). As you know, that Throwable is the super class of Exception and Error class in Java. When you add errors in this way, these errors will be logged in JUnit test result .

To understand more on Error Collector, see below code example which demonstrates how to create an Error Collector object and add all the errors in that object to track the issue :


package guru99.junit;        

import org.junit.Rule;       

import org.junit.Test;       

import org.junit.rules.ErrorCollector;     

 public class ErrorCollectorExample {               


    public ErrorCollector collector = new ErrorCollector();                           


    public void example() {                   

    collector.addError(new Throwable(“There is an error in first line”));                           

    collector.addError(new Throwable(“There is an error in second line”));                           


                not(containsString(“here is an error”)));           

    // all lines of code will execute and at the end a combined failure will        

    be logged in.