JerseyTest 和 JUnit 抛出 NullPointerException

2022-09-02 02:38:19

我对球衣测试框架有一些问题。如果我使用@Before并@After注释,则目标方法将引发 NullPointerException。我以为 JerseyTest 可以与 JUnit 一起使用?我的问题在哪里?

  • 泽西岛: 2.12
  • JUnit: 4.11

失败的代码:

public class MyResourceTest extends JerseyTest {
    @Before
    public void setUp() { }

    @After
    public void tearDown() { }

    @Override
    protected Application configure() {
        return new ResourceConfig(MyResource.class);
    }

    @Test
    public void SHOULD_RETURN_BAD_REQUEST() throws IOException {
        System.out.println(target("myPath"));
        assertEquals(1, 1);
    }
}

结果:

java.lang.NullPointerException at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:566) at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:580) at foo.bar.MyResourceTest.SHOULD_RETURN_BAD_REQUEST(MyResourceTest.java:43)

有效的代码:

public class MyResourceTest extends JerseyTest {
    @Override
    protected Application configure() {
        return new ResourceConfig(MyResource.class);
    }

    @Test
    public void SHOULD_RETURN_BAD_REQUEST() throws IOException {
        System.out.println(target("myPath"));
        assertEquals(1, 1);
    }
}

结果:

JerseyWebTarget { http://localhost:9998/myPath }

答案 1

您的方法似乎覆盖了在父级中进行的一些重要初始化。尝试以不同的方式命名它们。例如:JerseyTest

@Before
public void setUpChild() { }

@After
public void tearDownChild() { }

答案 2

我来到这里是因为我正在使用JUnit 5,它似乎没有看到@Before,并且在JerseyTest设置/拆解方法上@After注释。我不得不覆盖它们并使用新的JUnit 5注释

public class MyResourceTest extends JerseyTest {
    @BeforeEach
    @Override
    public void setUp() throws Exception {
        super.setUp();
    }

    @AfterEach
    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(MyResource.class);
    }

    @Test
    public void SHOULD_RETURN_BAD_REQUEST() throws IOException {
        System.out.println(target("myPath"));
        assertEquals(1, 1);
    }
}

推荐