为什么 JUnit 运行 测试两次却得到不同的结果

Why does JUnit run tests twice with different resuls

当从 Eclipse 运行ning JUnit 时(使用右键单击 | 运行 as - 在项目级别和个人测试级别的结果相同)我测试 运行 两次。一次测试 运行 符合预期(并且仅标有包名称),另一次我得到虚假的空指针异常(并标有完全限定的包名称)。我没有任何套件,运行s 上的不同结果意味着它似乎不是 the same issue that others are having with tests running twice

我的测试文件(减去导入)是:

public class CommandHistoryTest extends TestCase {
    private CommandHistory commandHistory;

    @BeforeEach
    public void initEach() {
        commandHistory = new CommandHistory();
    }

    @Test
    @DisplayName("On creation, canUndo and canRedo should be false")
    public void testCreate() {
        Assertions.assertFalse(commandHistory.canUndo());
        Assertions.assertFalse(commandHistory.canRedo());
    }
}

正如我所说,这在其中一个 JUnit 传递上运行良好——它失败了,直到我实现了 commandHistory 的相关位并在我实现它们时通过了——但在另一个传递上它给了我一个 null Assertions.assertFalse(commandHistory.canUndo());

指针异常

我可以接受这一点,因为我得到了一组有效的测试结果,但在第二次通过时看到所有这些危险信号让我很难过。如何停止虚假测试?

编辑:我注意到在包资源管理器中,测试显示为“> CommandHistoryTest.java”。我添加了另一个测试 class,它不会在包资源管理器中显示“>”符号,也不会 运行 两次。 “>”是什么意思?

再次编辑:不,我现在看到“>”是 git 集成的一部分,但答案如下。

JUnit 运行对您的测试进行了两次:一次使用 Vintage 引擎,因为它从 JUnit 3 扩展 TestCase,一次使用 Jupiter 引擎,因为它包含一个用 org.junit.jupiter.api.Test 注释的方法.后者执行 @BeforeEach 方法,而前者不执行。只需删除 extends TestCase,它只会 运行 一次。