testng和junit有啥优缺点,该怎样选择

英文原文地址:JUnit 4 Vs TestNG比较
JUnit 4 Vs TestNG - Comparison中文译者:付学良 JUnit 4 与 TestNG 对比

JUnit 4和TestNG都是Java中非常受欢迎的单元测试框架。两种框架在功能上看起来非常相似。 哪一个更好? 在Java项目中应该使用哪个单元测试框架?
下面表中概括了JUnit 4和TestNG之间的功能比较。如下图所示 –

testng和junit有啥优缺点,该怎样选择


1. 注解支持注释/注解支持在JUnit 4和TestNG中是非常类似的。
JUnit4和TestNG之间的主要注释差异是:
在JUnit 4中,我们必须声明“@BeforeClass”和“@AfterClass”方法作为静态方法。 TestNG在方法声明中更灵活,它没有这个约束。3个额外的setUp / tearDown级别:suite和group(@Before / AfterSuite,@Before / After Test,@Before / After Group)。JUnit 4
@BeforeClasspublic static void oneTimeSetUp() { // one-time initialization code System.out.println("@BeforeClass - oneTimeSetUp");}Java
TestNG
@BeforeClasspublic void oneTimeSetUp() { // one-time initialization code System.out.println("@BeforeClass - oneTimeSetUp");}Java
在JUnit 4中,注释命名约定有点混乱,例如“Before”,“After”和“Expected”,我们并不真正了解“Before”和“After”之前的内容,以及要测试中的“预期” 方法。TestiNG更容易理解,它使用类似“BeforeMethod”,“AfterMethod”和“ExpectedException”就很明了。
2. 异常测试“异常测试”是指从单元测试中抛出的异常,此功能在JUnit 4和TestNG中都可实现。
JUnit 4
@Test(expected = ArithmeticException.class)public void divisionWithException() { int i = 1/0;}Java
TestNG
@Test(expectedExceptions = ArithmeticException.class)public void divisionWithException() { int i = 1/0;}Java
3. 忽略测试“忽略”表示是否应该忽略单元测试,该功能在JUnit 4和TestNG中均可实现。
JUnit 4
@Ignore("Not Ready to Run")@Testpublic void divisionWithException() { System.out.println("Method is not ready yet");}Java
TestNG
@Test(enabled=false)public void divisionWithException() { System.out.println("Method is not ready yet");}Java
4. 时间测试“时间测试”表示如果单元测试所花费的时间超过指定的毫秒数,则测试将会终止,并将其标记为失败,此功能在JUnit 4和TestNG中均可实现。
JUnit 4
@Test(timeout = 1000)public void infinity() { while (true);}Java
TestNG
@Test(timeOut = 1000)public void infinity() { while (true);}Java
5. 套件测试“套件测试”是指捆绑几个单元测试并一起运行。 此功能在JUnit 4和TestNG中都可实现。 然而,两者都使用非常不同的方法来实现它。
JUnit 4
“@RunWith”和“@Suite”用于运行套件测试。下面的类代码表示在JunitTest5执行之后,单元测试“JunitTest1”和“JunitTest2”一起运行。 所有的声明都是在类内定义的。
@RunWith(Suite.class)@Suite.SuiteClasses({ JunitTest1.class, JunitTest2.class})public class JunitTest5 {}


推荐阅读