Skip to content

Working with JUnit ErrorCollector

A common practice when developing tests with JUnit is to use assertions. But this comes with a drawback, since when an assert fails, the whole test fails, leaving some tests conditions untested. The ErrorCollector comes to address this problem. As its name suggests, it collects all the assert statements. When an assert failure is found it proceeds with the next statements and only returns the failure at the end of the test.


import static org.hamcrest.CoreMatchers.equalTo;
import static;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class TestErrorCollector {
    public final ErrorCollector collector = new ErrorCollector();

    public void testWithAssert() {
        assertEquals(1, 2);

    public void testWithErrorCollector() {
        collector.checkThat(1, equalTo(2));
        collector.checkThat(true, is(false));
        collector.checkThat(false, is(false));


The method testWithAssert will produce the following result:

The above result means that assertEquals(1, 2) failed and the following assert statements were not tested.

The method testWithErrorCollector will produce the following result:

The above result means that all assert statements were tested two failed and one has passed the test


  • JUnit rule ErrorCollector allows test continuity even after one test condition has failed
  • Test continuity and recovery is crucial for a test automation process
  • All errors will be reported at the end of test
  • Don’t forget to add @Rule annotation
  • ErrorCollector must be public, otherwise it will throws a ValidationError
Published inUnit Test

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *