digitig
digitig

Reputation: 2140

Why does JUnit run tests twice with different resuls

When running JUnit from Eclipse (using right-click | run as - same results at project level and individual test level) my tests run twice. One time the tests run as expected (and are labelled with just the package name), the other time I get spurious null pointer exceptions (and labelled with the fully qualified package name). I don't have any suites, and the different results on the runs mean that it doesn't seem to be the same issue that others are having with tests running twice.

My test file (minus the imports) is:

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

As I say, this works fine on one of the JUnit passes - it failed until I implemented the relevant bits of commandHistory and passed when I implemented them - but on the other pass it gives me a null pointer exception on Assertions.assertFalse(commandHistory.canUndo());

I can live with this, because I am getting a valid set of test results, but seeing all those red flags on the second pass makes me sad. How do I stop the spurious tests?

EDIT: I note that in the package explorer the test shows as '> CommandHistoryTest.java'. I've added another test class, which doesn't show that '>' symbol in the package explorer and which doesn't run twice. What does the '>' mean?

EDIT AGAIN: No, I now see that '>' was part of the git integration, but the answer is below.

Upvotes: 2

Views: 3121

Answers (1)

Marc Philipp
Marc Philipp

Reputation: 1908

JUnit runs your test twice: once with the Vintage engine because it extends TestCase from JUnit 3 and once with the Jupiter engine because it contains a method annotated with org.junit.jupiter.api.Test. While the latter executes the @BeforeEach method, the former does not. Just remove extends TestCase and it will only run once.

Upvotes: 8

Related Questions