org.hamcrest.junit.ErrorCollector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hamcrest-junit Show documentation
Show all versions of hamcrest-junit Show documentation
Classes to use Hamcrest matchers within JUnit tests
The newest version!
package org.hamcrest.junit;
import static org.hamcrest.junit.MatcherAssert.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.hamcrest.Matcher;
import org.junit.rules.Verifier;
import org.junit.runners.model.MultipleFailureException;
/**
* 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):
*
*
* public static class UsesErrorCollectorTwice {
* @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"));
* collector.checkThat(getResult(), not(containsString("ERROR!")));
* // all lines will run, and then a combined failure logged at the end.
* }
* }
*
*
* @since 4.7
*/
public class ErrorCollector extends Verifier {
private List errors = new ArrayList();
@Override
protected void verify() throws Throwable {
MultipleFailureException.assertEmpty(errors);
}
/**
* Adds a Throwable to the table. Execution continues, but the test will fail at the end.
*/
public void addError(Throwable error) {
errors.add(error);
}
/**
* Adds a failure to the table if {@code matcher} does not match {@code value}.
* Execution continues, but the test will fail at the end if the match fails.
*/
public void checkThat(final T value, final Matcher matcher) {
checkThat("", value, matcher);
}
/**
* Adds a failure with the given {@code reason}
* to the table if {@code matcher} does not match {@code value}.
* Execution continues, but the test will fail at the end if the match fails.
*/
public void checkThat(final String reason, final T value, final Matcher matcher) {
checkSucceeds(new Callable