Java JUnit 混淆:使用“扩展 TestCase”还是“@Test”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2635839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:10:12  来源:igfitidea点击:

JUnit confusion: use 'extends TestCase' or '@Test'?

javajunitautomated-tests

提问by Rabarberski

I've found the proper use (or at least the documentation) of JUnit very confusing. This question serves both as a future reference and as a real question.

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

If I've understood correctly, there are two main approaches to create and run a JUnit test:

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

Approach A (JUnit 3-style):create a class that extends TestCase, and start test methods with the word test. When running the class as a JUnit Test (in Eclipse), all methods starting with the word testare automatically run.

方法 A(JUnit 3 风格):创建一个扩展 TestCase 的类,并以单词 开始测试方法test。当将类作为 JUnit 测试(在 Eclipse 中)运行时,所有以单词开头的方法都会test自动运行。

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);
    }
}

Approach B (JUnit 4-style):create a 'normal' class and prepend a @Testannotation to the method. Note that you do NOT have to start the method with the word test.

方法 B(JUnit 4 风格):创建一个“普通”类并@Test在方法前添加一个注释。请注意,您不必以单词test.

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);
    }
}

Mixing the two seems not to be a good idea, see e.g. this stackoverflow question:

将两者混合似乎不是一个好主意,请参阅例如这个 stackoverflow 问题

Now, my questions(s):

现在,我的问题:

  1. What is the preferred approach, or when would you use one instead of the other?
  2. Approach B allows for testing for exceptions by extending the @Test annotation like in @Test(expected = ArithmeticException.class). But how do you test for exceptions when using approach A?
  3. When using approach A, you can group a number of test classes in a test suite like this:

    TestSuite suite = new TestSuite("All tests");
    suite.addTestSuite(DummyTestA.class);
    suite.addTestSuite(DummyTestAbis.class);

    But this can't be used with approach B (since each testclass should subclass TestCase). What is the proper way to group tests for approach B?

  1. 什么是首选方法,或者您何时会使用一种方法而不是另一种方法?
  2. 方法 B 允许通过扩展 @Test 注释来测试异常@Test(expected = ArithmeticException.class)但是在使用方法 A 时如何测试异常?
  3. 使用方法 A 时,您可以在测试套件中对多个测试类进行分组,如下所示:

    TestSuite suite = new TestSuite("All tests");
    suite.addTestSuite(DummyTestA.class);
    suite.addTestSuite(DummyTestAbis.class);

    但这不能与方法 B 一起使用(因为每个测试类都应该子类化 TestCase)。对方法 B 进行分组测试的正确方法是什么?

Edit: I've added the JUnit versions to both approaches

编辑:我已将 JUnit 版本添加到这两种方法中

采纳答案by Joachim Sauer

The distinction is rather easy:

区别很简单:

  • extending TestCaseis the way unit tests were written in JUnit 3 (of course it's still supported in JUnit 4)
  • using the @Testannotation is the way introduced by JUnit 4
  • 扩展TestCase是在 JUnit 3 中编写单元测试的方式(当然 JUnit 4 仍然支持它)
  • 使用@Test注解是JUnit 4引入的方式

Generally you should choose the annotation path, unless compatibility with JUnit 3 (and/or a Java version earlier than Java 5) is needed. The new way has several advantages:

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

To test for expected exceptions in a JUnit 3 TestCaseyou'd have to make the text explicit.

要在 JUnit 3 中测试预期的异常,TestCase您必须使文本显式。

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

JUnit 5introduced yet another API change, but still uses annotations. The new @Testannotation is org.junit.jupiter.api.Test(the "old" JUnit 4 one was org.junit.Test), but it works pretty much the same as the JUnit 4 one.

JUnit 5引入了另一个 API 更改,但仍然使用注释。新的@Test注释是org.junit.jupiter.api.Test(“旧的”JUnit 4注释org.junit.Test),但它的工作方式与 JUnit 4 的注释几乎相同。

回答by Grimmy

I have a preference for JUnit 4 (Annotation approach) because I find it more flexible.

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

If you want to build test suite in JUnit 4, you have to create a class grouping all tests like this:

如果要在 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 */
}

回答by black666

  1. The "preferred" approach would be to use annotations which have been introduced since Junit 4. They make a lot of things easier (see your second question)

  2. You can use a simple try/catch block for that:

  1. “首选”方法是使用自 Junit 4 以来引入的注释。它们使很多事情变得更容易(请参阅您的第二个问题)

  2. 您可以为此使用一个简单的 try/catch 块:


public void testForException() {
    try {
        Integer.parseInt("just a string");
        fail("Exception should have been thrown");
    } catch (final Exception e) {
        // expected
    }
}

回答by Espen

You should use JUnit 4. It's better.

您应该使用 JUnit 4。它更好。

Much frameworks have started to deprecate the JUnit 3.8 support.

许多框架已经开始弃用 JUnit 3.8 支持。

This is from the Spring 3.0 reference documentation:

这是来自 Spring 3.0 参考文档:

[Warning] Legacy JUnit 3.8 class hierarchy is deprecated

[警告] 旧版 JUnit 3.8 类层次结构已弃用

In general, you should always try to use the latest stable release of a framework when you start something new.

一般而言,当您开始新事物时,您应该始终尝试使用框架的最新稳定版本。

回答by Yishai

There is an unanswered part to your question, and that is "What is the proper way to group tests for approach B?"

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

The official answer is that you annotate a class with an @RunWith(Suite.class) and then use the @Suite.SuiteClasses annotation to list the classes. This is how the JUnit developers do it (listing every class in a suite manually). In many ways this approach is an improvement, in that it is trivial and intuitive to add before suite and after suite behaviors (just add an @BeforeClass and @AfterClass method to the the class annotated with the @RunWith - much better than the old TestFixture).

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

However, it does have a step backwards, in that annotations don't allow you to dynamically create the list of classes, and working around that problem gets a bit ugly. You have to subclass the Suite class and dynamically create the array of classes in the subclass and pass it to the Suite constructor, but this is an incomplete solution in that other subclasses of Suite (such as Categories) don't work with it and essentially do not support dynamic Test class collection.

但是,它确实倒退了一步,因为注释不允许您动态创建类列表,并且解决该问题变得有点难看。您必须对 Suite 类进行子类化并在子类中动态创建类数组并将其传递给 Suite 构造函数,但这是一个不完整的解决方案,因为 Suite 的其他子类(例如 Categories)不能使用它,并且基本上不支持动态测试类集合。