前言
在写单元测试的时候,经常会遇到需要断言方法需要抛出一个异常这种场景,这时,就会用到Junit的异常测试功能
方式
1.使用@Test注解自带的 expected 属性来断言需要抛出一个异常,如下:
@Test(expected = IllegalStateException.class) public void testExpect() { throw new IllegalStateException(); } |
在运行测试的时候,此方法必须抛出异常,这个测试才算通过,反之则反。
2.使用ExpectedException类来进行打桩,我更喜欢这种方式,因为这种方式不仅能判断出指定的异常,并且还能对消息进行判断,并使用一些匹配器来匹配,比较灵活,如下
先定义一个公共成员变量
@Rule
public ExpectedException thrown = ExpectedException.none();
在方法中抛出异常
@Test public void testThrown() { thrown.expect(IllegalStateException.class); thrown.expectMessage("illegal"); throw new IllegalStateException("illegal"); } |
还能够使用匹配器来匹配
@Test public void testThrownMessageMatch() { thrown.expect(IllegalStateException.class); thrown.expectMessage(startsWith("illegal")); throw new IllegalStateException("illegal xxx"); } |