Skip to content

Instantly share code, notes, and snippets.

@renatoathaydes
Last active February 15, 2016 14:01
Show Gist options
  • Save renatoathaydes/6907103 to your computer and use it in GitHub Desktop.
Save renatoathaydes/6907103 to your computer and use it in GitHub Desktop.
ThrownMatcher is a Hamcrest matcher that can be used to verify a Throwable of a certain type has been thrown.
package com.athaydes.automaton.internal;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.junit.internal.matchers.TypeSafeMatcher;
/**
* User: Renato
*/
public class ThrownMatcher extends TypeSafeMatcher<Runnable> {
private final String expected;
private String actual;
public ThrownMatcher( String s ) {
expected = s;
}
@Factory
public static Matcher<Runnable> thrown( Class<? extends Throwable> expected ) {
return new ThrownMatcher( expected.getName() );
}
@Override
public boolean matchesSafely( Runnable action ) {
try {
action.run();
actual = "nothing";
return false;
} catch ( Throwable t ) {
actual = t.getClass().getName();
return actual.equals( expected );
}
}
@Override
public void describeTo( Description description ) {
description.appendText( "Should have thrown " + expected + " but threw " + actual );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment