近期整理代码的时候,总习惯把一些经常使用的工具类和方法等都写在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%在于做人的技术和技巧。和大众融洽地相处。以和谐取悦于人,留意尊重别人的立场,让每一个人都认为自己是重要的,也就得到了讨人喜欢的秘决了。