`

Junit4.8之Category

阅读更多
Junit已经更新到4.8.1了,动作还挺快的呀,可能是kent beck发现junit可能有点落后了。
的确,相对于TestNG来说,Junit的确有很多方面的局限,因此近年来,junit升级也变得飞快。
这里有一篇比较Junit与TestNG的文章:http://www.ibm.com/developerworks/cn/java/j-cq08296/

上面的那篇文章讲解了一些关于junit与testNG的区别,其实testNG还有一些很强大的功能,总的来说,TestNG肯定要比Junit强大,但随着junit的不断完善,与TestNG的差距也不是那么明显了,不得不承认,junit很多特性都借鉴了TestNG,包括4.8所更新的Category,先看看官方的例子:

public interface SlowTests {
}

public interface FastTests {
}


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

	@Category(SlowTests.class)
	@Test
	public void b() {		
		System.out.println("A b()");
	}
}


@Category( { SlowTests.class, FastTests.class })
public class B {
	@Test
	public void c() {
		System.out.println("B c()");
	}
}


上面的代码很简单,只要一个地方比较特别,那就是@Category,这个注解的作用(原文):
Marks a test class or test method as belonging to one or more categories of tests.
这句英文看起来简单,但又害怕翻译得不准确。那如何进行单元目录测试呢,见下面代码:

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


当然junit还有一个注解@ExcludeCategory,用法如下:
@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
}


4.8就增加了这么一个功能,总的来说,这个功能很不错,尤其测试的功能比较复杂时,知道TestNG的人会发现,它其实与TestNG的分组测试很相似。TestNG在很多方面可以超越Junit,但并不是说Junit就没什么前途,Junit并不需要做得像TestNG那么全面,把常用的功能做好就行了,除非需要非常全面的测试,不然没有必要非要赶上用TestNG不可。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics