`

Junit4使用汇总(一)基础

 
阅读更多

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

 

一、基础篇:

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

名称 用途
@Test 
方法前加,表示要执行的testcase
@Before tesecase 运行前执行
@After testcase运行后执行
@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

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics