代码之家  ›  专栏  ›  技术社区  ›  digitig

为什么junit用不同的结果运行两次测试

  •  1
  • digitig  · 技术社区  · 6 年前

    在eclipse中运行junit时(使用右键单击run-as-same结果在项目级和单独的测试级),我的测试运行两次。一次测试按预期运行(并仅用包名称标记),另一次我得到虚假的空指针异常(并用完全限定的包名称标记)。我没有套房,而且不同的结果表明 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 当我实现它们的时候就通过了-但是在另一个过程中它给了我一个空指针异常 Assertions.assertFalse(commandHistory.canUndo());

    我可以接受这个,因为我得到了一组有效的测试结果,但是看到第二关上的所有红旗让我很难过。我该如何阻止虚假的测试?

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

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

    1 回复  |  直到 6 年前
        1
  •  6
  •   Marc Philipp    6 年前

    junit运行您的测试两次:一次使用老式引擎,因为它扩展了 TestCase 来自junit 3和jupiter引擎,因为它包含一个注释为 org.junit.jupiter.api.Test . 当后者执行 @BeforeEach 方法,前者没有。刚刚删除 extends TestCase 它只会跑一次。