Last active
February 15, 2016 14:01
-
-
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.
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
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