se.fortnox.reactivewizard.test.TestUtil Maven / Gradle / Ivy
package se.fortnox.reactivewizard.test;
import org.assertj.core.api.AbstractThrowableAssert;
import org.mockito.ArgumentMatcher;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.argThat;
/**
* Utility functions for building tests.
*/
public final class TestUtil {
private TestUtil() {
}
/**
* Wraps a lambda expression which does assertions on your object.
*
* Example:
*
*
* verify(assignmentDao).createAssignment(matches((assignment -> {
* assertThat(assignment.getTitle()).isEqualTo("Assignment 1");
* assertThat(assignment.getClientId()).isEqualTo("501780");
* })));
*
*
* @param asserter a lambda expression doing assertions
* @param is the type of consumer value
* @return null
*/
public static T matches(Consumer asserter) {
return argThat(new ArgumentMatcher() {
Error error;
@SuppressWarnings("unchecked")
@Override
public boolean matches(Object argument) {
try {
asserter.accept((T) argument);
} catch (Error t) {
error = t;
return false;
}
return true;
}
@Override
public String toString() {
if (error != null) {
return error.getMessage();
}
return "";
}
});
}
/**
* Assert the type of an exception.
*
* @param The type of the expected exception
* @param throwable The exception to apply assertion on
* @param type Expected type of exception
* @return The assertion for further assertion chaining
*/
public static AbstractThrowableAssert assertNestedException(Throwable throwable, Class type) {
while (throwable != null && !type.isAssignableFrom(throwable.getClass())) {
Throwable cause = throwable.getCause();
if (cause == throwable || cause == null) {
fail("Expected exception of type " + type.getCanonicalName());
}
throwable = cause;
}
return assertThat(throwable);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy