Last active
September 25, 2019 12:04
-
-
Save tomwhoiscontrary/4fbf20350700d7e1c354b67d62b2895e to your computer and use it in GitHub Desktop.
ErrorCollector for JUnit 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.hamcrest.Matcher; | |
import org.hamcrest.MatcherAssert; | |
import org.junit.jupiter.api.extension.AfterTestExecutionCallback; | |
import org.junit.jupiter.api.extension.ExtensionContext; | |
import org.opentest4j.MultipleFailuresError; | |
import java.lang.reflect.Field; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class ErrorCollector { | |
public static class Extension implements AfterTestExecutionCallback { | |
@Override | |
public void afterTestExecution(ExtensionContext context) throws Exception { | |
if (context.getExecutionException().isPresent()) return; | |
ErrorCollector errorCollector = getOnlyField(context.getRequiredTestInstance(), ErrorCollector.class); | |
if (!errorCollector.failures.isEmpty()) { | |
throw new MultipleFailuresError(null, errorCollector.failures); | |
} | |
} | |
private <T> T getOnlyField(Object object, Class<T> fieldType) throws IllegalAccessException { | |
Class<?> cl = object.getClass(); | |
List<Field> fields = Arrays.stream(cl.getFields()) | |
.filter(f -> f.getType().equals(fieldType)) | |
.collect(Collectors.toList()); | |
if (fields.size() != 1) { | |
throw new AssertionError("there must be exactly one field of type " + fieldType.getName() + ": " + fields); | |
} | |
Field field = fields.get(0); | |
Object value = field.get(object); | |
return fieldType.cast(value); | |
} | |
} | |
private final List<Throwable> failures = new ArrayList<>(); | |
public <T> void checkThat(String reason, T value, Matcher<T> matcher) { | |
try { | |
MatcherAssert.assertThat(reason, value, matcher); | |
} catch (Throwable e) { | |
failures.add(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment