Junit的异常测试

方式1:

@Test(expected = IndexOutOfBoundsException.class) 
public void empty() { new ArrayList<Object>().get(0); }
解析:
@Test的注释有一个可选参数expected,它作为Throwable的子类,可以抛出异常。

方式2:
使用try...catch()..
@Test
public void testExceptionMessage() {
    try {
        new ArrayList<Object>().get(0); fail("Expected an IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) { assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0")); } }
方式3:
使用ExpectedException规则,此规则可以指示出异常和异常信息。
@Rule
public ExpectedException thrown = ExpectedException.none(); @Test public void shouldTestExceptionMessage() throws IndexOutOfBoundsException { List<Object> list = new ArrayList<Object>(); thrown.expect(IndexOutOfBoundsException.class); thrown.expectMessage("Index: 0, Size: 0"); list.get(0); // execution will never get past this line }

方式4:
使用Matchers检查异常
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestExy { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void shouldThrow() { TestThing testThing = new TestThing(); thrown.expect(NotFoundException.class); thrown.expectMessage(startsWith("some Message")); thrown.expect(hasProperty("response", hasProperty("status", is(404)))); testThing.chuck(); } private class TestThing { public void chuck() { Response response = Response.status(Status.NOT_FOUND).entity("Resource not found").build(); throw new NotFoundException("some Message", response); } } }
更多信息点击此链接:
https://github.com/junit-team/junit4/wiki/Exception-testing


转载于:https://www.cnblogs.com/woniu123/p/6366067.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值