且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-20 08:48:40

区别很简单:

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

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

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 TestCase 中测试预期的异常,您必须使文本显式.

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

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 5 引入了另一个 API 更改,但仍使用注释.新的 @Test 注释是 org.junit.jupiter.api.Test(旧"JUnit 4 是 org.junit.Test),但它的工作原理与 JUnit 4 几乎相同.

JUnit 5 introduced yet another API change, but still uses annotations. The new @Test annotation 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.