junit与异常
junit与异常
在单元测试中,如果期望被测试的方法抛出一个异常,那么可以使用@Test(expected = Exception.class)
Demo
源方法
public class ThrowException {
    public void throwExceptionWithoutThrow(){
        try{
            throw new NumberFormatException();
        }catch(Exception exception){
        }
    }
    public void throwExceptionWithThrow(){
        try{
            throw new NumberFormatException();
        }catch(Exception exception){
            throw exception;
        }
    }
}
测试类
public class ThrowExceptionTest {
    @InjectMocks
    private ThrowException throwException;
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }
    /**
     * 测试失败,因为catch中没有throw
     */
    @Test(expected = Exception.class)
    public void throwExceptionWithoutThrow(){
        throwException.throwExceptionWithoutThrow();
    }
    @Test
    public void throwExceptionWithoutThrowWithoutExpected(){
        throwException.throwExceptionWithoutThrow();
    }
    /**
     * 测试通过
     */
    @Test(expected = Exception.class)
    public void throwExceptionWithThrow(){
        throwException.throwExceptionWithThrow();
    }
    /**
     * 测试不通过,因为没有expected
     */
    @Test
    public void throwExceptionWithThrowWithoutExpected(){
        throwException.throwExceptionWithThrow();
    }
}
