更新时间:2023-11-20 08:48:40
区别很简单:
TestCase
是在 JUnit 3 中编写单元测试的方式(当然 JUnit 4 仍然支持它)@Test
注解是JUnit 4引入的方式TestCase
is the way unit tests were written in JUnit 3 (of course it's still supported in JUnit 4)@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:
@Test
注释 更明确,更容易在工具中支持(例如,通过这种方式可以轻松搜索所有测试)@Before注释多个方法代码>
/@BeforeClass
和 @After
/@AfterClass
提供更大的灵活性@Rule
注释ExpectedException
@Ignored
注释@RunWith 的替代测试运行器
要在 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.