Skip to content

Instantly share code, notes, and snippets.

@jarrodhroberson
Last active September 3, 2019 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarrodhroberson/01883f95cda427e54a028de43e0ed4fd to your computer and use it in GitHub Desktop.
Save jarrodhroberson/01883f95cda427e54a028de43e0ed4fd to your computer and use it in GitHub Desktop.
Custom IsEmpty Hamcrest Matcher
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