Skip to content

Instantly share code, notes, and snippets.

@caarlos0
Last active June 4, 2016 13:02
Show Gist options
  • Save caarlos0/ed1ef6d5d014175612fe to your computer and use it in GitHub Desktop.
Save caarlos0/ed1ef6d5d014175612fe to your computer and use it in GitHub Desktop.
An example of how to use JUnit `@Rule` to test methods who are expected to thrown an exception.
package sample;
import org.junit.*;
import org.junit.rules.ExpectedException;
import sample.*;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class MyClassTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testNoExceptionsExpected() throws Exception {
asserThat(new MyClass().thisWillWork(), notNullValue());
}
@Test
public void testExpectedMyException() throws Exception {
exception.expect(MyException.class);
new MyClass().thisWillFail();
}
}
@roberto-filho
Copy link

roberto-filho commented Jun 4, 2016

Is the @Rule annotation new in junit4?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment