问题

我发现JUnit的正确使用(或至少是文档)非常令人困惑。这个问题既是未来的参考,也是一个真实的问题。

如果我理解正确,有两种主要的方法来创建和运行JUnit测试:

**方法A(JUnit 3-style):**创建一个扩展TestCase的类,并使用wordtest启动测试方法。当将类作为JUnit Test运行时(在Eclipse中),所有以wordtest开头的方法都会自动运行。

import junit.framework.TestCase;

public class DummyTestA extends TestCase {

    public void testSum() {
        int a = 5;
        int b = 10;
        int result = a + b;
        assertEquals(15, result);
    }
}

**方法B(JUnit 4-style):**创建一个'普通'类并在方法前加一个@Testannotation。请注意,你不必使用wordtest启动该方法。

import org.junit.*;
import static org.junit.Assert.*;

public class DummyTestB {

    @Test
    public void Sum() {
        int a = 5;
        int b = 10;
        int result = a + b;
        assertEquals(15, result);
    }
}

混合两者似乎不是一个好主意,参见例如.4441818:

现在,我的问题:

  • 什么是首选方法,或者何时使用其中一种而不是另一种?
  • 方法B允许通过像@Test(expected = ArithmeticException.class)中那样扩展@Test注释来测试异常。但是,在使用方法A时,如何测试异常?
  • 使用方法A时,你可以在测试套件中对许多测试类进行分组,如下所示:TestSuite suite = new TestSuite("All tests"); suite.addTestSuite(DummyTestA.class); suite.addTestSuite(DummyTestAbis.class);但这不能用于方法B(因为每个测试类应该是TestCase的子类)。对方法B进行分组测试的正确方法是什么?

编辑:我已经为这两种方法添加了JUnit版本


#1 热门回答(99 赞)

区别很简单:

  • 扩展TestCase是单元测试在JUnit 3中编写的方式(当然它仍然在JUnit 4中得到支持)
  • 使用@Test注释是JUnit 4引入的方式

通常,你应该选择注释路径,除非需要与JUnit 3(和/或Java 5之前的Java版本)兼容。新方法有几个优点:

  • @Test annotaton更明确,更容易在工具中支持(例如,以这种方式搜索所有测试很容易)
  • 可以使用@ Before / @ BeforeClass和@ After / @ AfterClass注释多个方法,从而提供更大的灵活性
  • 支持ExpectedException之类的@Rule注释
  • 支持@Ignored注释
  • 使用@RunWith支持替代测试跑步者

要测试JUnit中的预期异常3TestCase,你必须使文本明确。

public void testMyException() {
  try {
    objectUnderTest.myMethod(EVIL_ARGUMENT);
    fail("myMethod did not throw an Exception!");
  } catch (MyException e) {
    // ok!
    // check for properties of exception here, if desired
  }
}

#2 热门回答(22 赞)

我更喜欢JUnit 4(Annotation方法),因为我发现它更灵活。

如果要在JUnit 4中构建测试套件,则必须创建一个类,对所有测试进行分组,如下所示:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;


@RunWith(Suite.class)
@SuiteClasses({
    Test1.class,
    Test2.class,
    Test3.class,
    Test4.class
})public class TestSuite
{
 /* empty class */
}

#3 热门回答(14 赞)

你的问题有一个未解答的部分,那就是"对方法B进行分组测试的正确方法是什么?"

官方答案是你使用@RunWith(Suite.class)注释类,然后使用@ Suite.SuiteClasses批注列出类。这就是JUnit开发人员如何做到这一点(手动列出套件中的每个类)。在许多方面,这种方法是一种改进,因为在套件和套件后行为之前添加它是微不足道和直观的(只需将@BeforeClass和@AfterClass方法添加到使用@RunWith注释的类中 - 比旧的TestFixture更好)。

但是,它确实有一个倒退,因为注释不允许你动态创建类列表,并且解决该问题会变得有点难看。你必须继承Suite类并在子类中动态创建类的数组并将其传递给Suite构造函数,但这是一个不完整的解决方案,因为Suite的其他子类(如Categories)不能与它一起使用不支持动态Test类集合。


原文链接