Last active
September 3, 2019 00:10
-
-
Save jarrodhroberson/01883f95cda427e54a028de43e0ed4fd to your computer and use it in GitHub Desktop.
Custom IsEmpty Hamcrest Matcher
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.Description; | |
import org.hamcrest.Factory; | |
import org.hamcrest.Matcher; | |
import org.hamcrest.TypeSafeMatcher; | |
import javax.annotation.Nonnull; | |
import java.lang.reflect.InvocationTargetException; | |
/** Matches any class that has an <code>isEmpty()</code> method | |
* that returns a <code>boolean</code> | |
* */ | |
public class IsEmpty<T> extends TypeSafeMatcher<T> | |
{ | |
@Factory | |
public static <T> Matcher<T> empty() { return new IsEmpty<T>(); } | |
@Override | |
protected boolean matchesSafely(@Nonnull final T item) | |
{ | |
try | |
{ | |
return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); | |
} | |
catch (final NoSuchMethodException e) { return false; } | |
catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } | |
} | |
@Override | |
public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment