2012-10-24 64 views
2

當在JUnit 4中,你可以使用@Test(expected = SomeException.class)註釋申報預期異常期待例外。然而,當測試用理論做,@Theory批註沒有預期財產。使用JUnit理論

什麼是測試理論時申報預期異常的最好方法?

回答

5

我更喜歡使用ExpectedExceptionrule

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 
} 
1

您也可以使用普通assert。您可以使用它在舊版本的JUnit(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"); 
    } 
}