使用@BeforeAll实例化JUnit中的对象将返回null

问题描述

这似乎很容易,而且我不明白自己在做什么错。我正在使用@BeforeAll标记创建一个新的Sequence对象,并在每个测试方法中使用该实例。但是,似乎Sequence对象为null,我不明白为什么。我确保@BeforeAll方法是静态的。

public class SequenceTest {
    static Sequence seq;

    @BeforeAll
    public static void createTestSequence() {

        seq =  new Sequence();
        assertEquals(null,seq);  // this passes when it shouldn't!
    }

    @Test
    public void test1() {
        // do test 
        // fails because Sequence object is null
    }
}

我正在使用maven,并将这些依赖项包含在pom.xml文件中:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
</plugin>

<!-- junit 5,unit test -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.3.1</version>
    <scope>test</scope>
</dependency>

解决方法

我认为您的阻止代码应该起作用。也许您的Maven Fire插件没有运行任何测试?我尝试使用以下块代码,但测试失败:

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;


import static org.junit.jupiter.api.Assertions.assertEquals;

public class SequenceTest {
    static Sequence seq;

    @BeforeAll
    static void createTestSequence() {

        seq =  new Sequence();
        assertEquals(null,seq);  // this passes when it shouldn't!
    }

    @Test
    public void test1() {
        // do test
        // fails because Sequence object is null
    }
}

class Sequence{

}

我遇到以下错误:

预期:但是是:org.tdd.others.Sequence@9b7af25 org.opentest4j.AssertionFailedError:预期:但是是: org.tdd.others.Sequence@9b7af25,网址为 org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)在 org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62) 在 org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182) 在 org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177) 在 org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124) 在 org.tdd.others.SequenceTest.createTestSequence(SequenceTest.java:16) 在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处

,

我正在使用旧的依赖项。更改为此:

          <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
            </plugin>

       <!-- junit 5,unit test -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.4.0</version>
            <scope>test</scope>
        </dependency>