Junit4使用汇总(一)基础

看了三天的Junit,基本用法汇如下:

 

一、基础篇:

 JUnit4引入了Java5的注释Annotation。常用的注释如下:

名称用途
@Test 
方法前加,表示要执行的testcase
@Beforetesecase 运行前执行
@Aftertestcase运行后执行
@BeforeClass类运行前执行
 @AfterClass类运行后执行
@Ignore表示暂时不想执行这个testcase
@RunWith  指定一个Runner来运行你的代码
@Rule 后面有专门分析
  

更详细及相关例子可参考

http://blog.csdn.net/ccjjyy/article/details/6175498

 

二、JUnit4的核心之一:断言

   assertArrayEquals
   assertEquals     : expected.equals(actual) 

   assertSame       :expected == actual
   assertFalse
   assertNotNull
   assertNotSame
   assertNull
   assertThat org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("b")));
    org.junit.Assert.assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
    org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString  ("n")));
  assertThat("good", allOf(equalTo("good"), startsWith("good")));
    assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
    assertThat("good", anyOf(equalTo("bad"), equalTo("good")));
    assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));
    assertThat(new Object(), not(sameInstance(new Object()))); 

 

 三、对异常的测试

 @Test注释有一个可选参数expected,这个参数的取值是Throwable的子类。如果我们想判断上面的代码是否抛出正确的异常。

代码:

 

@Test(expected= IndexOutOfBoundsException.class) 
public void empty() { 
    new ArrayList<Object>().get(0); 
}

 也可以利用Rule,代码:

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

 

说明:

  1. 利用@Rule,我们可以对异常的提示信息进行检查。
  2. expectMessage方法还支持使用CoreMatchers.containsString来进行提示信息的匹配判断,如下:

     thrown.expectMessage(CoreMatchers.containsString("Size: 0"));

四、测试超时

通过@Test注释的一个可选参数timeout的数值(单位毫秒),我们可以告诉框架,预设的超时时间是多少。当测试运行中,执行时间超出了这个预设值,框架就会抛出TimeoutException异常,标记这个测试失败了。

@Test(timeout=1000)
public void testWithTimeout() {
  ...
}

 我们也可以使用规则,来为整个测试类里面所有测试方法设置一个统一的超时时间

@Rule
    public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值