In JUnit 4 you can declare expected exception using @Test(expected = SomeException.class)
annotation. However, when testing is done using Theories, @Theory
annotation does not have expected property.
What is the best way to declare expected exception when testing Theories?
I prefer using ExpectedException rule :
import org.junit.rules.ExpectedException;
<...>
@Rule
public ExpectedException thrown = ExpectedException.none();
@Theory
public void throwExceptionIfArgumentIsIllegal(Type type) throws Exception {
assumeThat(type, equalTo(ILLEGAL));
thrown.expect(IllegalArgumentException.class);
//perform actions
}
Also you can use a normal assert
. You can use it on older versions of JUnit (before 4.9).
@Test
public void exceptionShouldIncludeAClearMessage() throws InvalidYearException {
try {
taxCalculator.calculateIncomeTax(50000, 2100);
fail("calculateIncomeTax() should have thrown an exception.");
} catch (InvalidYearException expected) {
assertEquals(expected.getMessage(),
"No tax calculations available yet for the year 2100");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.