您的位置:首页 > 其它

Junit4.x高级用法详解(一)

2014-06-19 13:47 309 查看
最近整理代码的时候,总习惯把一些常用的工具类和方法等都写在junit中,这样可以方便于在想用的时候直接copy,在用junit的时候学到了一些比较有用的东西,记录如下:

1.使用junit进行超时测试

@Test(timeout=2000)

public void testTimeout() throws InterruptedException {

Thread.sleep(2000);

}

@Test(timeout=2000)

public void testTimeout() throws InterruptedException {

Thread.sleep(2001);

}

2.使用junit进行异常测试

@Test(expected=IOException.class)

public void testExceptions() throws InterruptedException {

throw new RuntimeException();

}





@Test(expected=RuntimeException.class)

public void testExceptions2() throws InterruptedException {



throw new RuntimeException();

}

3.使用junit进行参数测试

private SimpleDateFormat sdf;

private String date;

private String dateformat;

private String expectedDate;







public TestJunitParameter(String date, String dateformat,

String expectedDate) {

this.date = date;

this.dateformat = dateformat;

this.expectedDate = expectedDate;

}



@Parameters

public static Collection getParamters() {

String[][] object = {

{ "2011-07-01 00:20:20", "yyyyMMdd", "20110701" },

{ "2011-07-01 00:20:20", "yyyy年MM月dd日", "2011年07月01日" },

{ "2011-07-01 00:20:20", "HH时mm分ss秒", "00时20分20秒" } };

List<String[]> list = Arrays.asList(object);

return list;

}

@Test

public void testJunitParameter() throws ParseException {

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date d = df.parse(this.date);

sdf = new SimpleDateFormat(this.dateformat);

String result = sdf.format(d);

Assert.assertEquals(this.expectedDate, result);

}

4.使用junit进行Suite测试,不仅仅TestNg可以有suite哦~~~

@RunWith(Suite.class)

@SuiteClasses({TestDateFormat.class,TestIORead.class})

public class TestSuite {





}

5.使用junit进行mock测试

mock测试其实采用的Mockito进行,所以这里不记录了,将会有一个页单独的介绍Mockito.

6.使用@Category进行分类测试

public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

public class A {
  @Test
  public void a() {
    fail();
  }

  @Category(SlowTests.class)
  @Test
  public void b() {
  }
}

@Category({SlowTests.class, FastTests.class})
public class B {
  @Test
  public void c() {

  }
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
 // Will run A.b and B.c, but not A.a
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b, but not A.a or B.c
}



注:虽然Class B 也包含了SlowTests.class,但是其同时也包含了FastTests.class,因为我们在测试类的注解上加了@ExcludeCategory(FastTests.class),所以Class B的c方法是不会执行的

成就与否,15%在于个人的才干和技能,而85%在于做人的技术和技巧。和大众融洽地相处,以和谐取悦于人,留意尊重别人的立场,让每个人都觉得自己是重要的,也就得到了讨人喜欢的秘决了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: