Last active
April 24, 2016 23:28
-
-
Save jeffypooo/9b906074967a8ca55d8a3a1eca2bafd0 to your computer and use it in GitHub Desktop.
Some custom exception matchers for hamcrest
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.BaseMatcher; | |
import org.hamcrest.Description; | |
import org.hamcrest.Matcher; | |
/** | |
* Hamcrest matchers for exceptions | |
*/ | |
public class ExceptionMatchers { | |
public static Matcher<? super Exception> hasMessage(final String msg) { | |
return new BaseMatcher<Exception>() { | |
@Override | |
public boolean matches(Object item) { | |
return ((Exception) item).getMessage().equals(msg); | |
} | |
@Override | |
public void describeTo(Description description) { | |
description.appendText("expecting exception message: " + msg); | |
} | |
}; | |
} | |
public static Matcher<? super Exception> hasCause(final Throwable cause) { | |
return new BaseMatcher<Exception>() { | |
@Override | |
public boolean matches(Object item) { | |
Exception other = (Exception) item; | |
if (other.getCause() == null) { | |
return false; | |
} | |
return other.getCause().equals(cause); | |
} | |
@Override | |
public void describeTo(Description description) { | |
description.appendText("expected cause throwable: " + cause); | |
} | |
@Override | |
public void describeMismatch(Object item, Description description) { | |
description.appendText("but was throwable: " + ((Exception) item).getCause()); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment