java Jersey测试在目标(…)处从主包>NullPointerException运行方法时失败
所以我用这个例子测试了它:
路径:pkg > src > test > java > rest > SimpleJerseyTest
public class SimpleJerseyTest extends JerseyTest {
@Path("hello")
public static class HelloResource {
@GET
public String getHello() {
return "Hello World!";
}
}
@Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
@Test
public void test() {
Response response = target("hello").request().get();
assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class);
System.out.println("Gotten response: " + content);
assertEquals("Content of ressponse is: ", "Hello World!", content);
}
}
这是测试的输出:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jul 24, 2020 11:29:07 AM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Gotten response: Hello World!
Jul 24, 2020 11:29:08 AM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]
Process finished with exit code 0
但是,当我将REST服务类放在主包中时,它不再工作(NullPointerException):
包:pkg > src > main > java > rest > BookService
@Path("books")
public class BookService {
@GET
public String getAll() {
return "test";
}
}
然后测试:
包:pkg > src > test > rest > BookServiceTest
class BookServiceTest extends JerseyTest {
@Override
protected Application configure() {
return new ResourceConfig(BookService.class);
}
@Test
void get() {
Response response = target("books").request().get();
}
}
这是测试的输出:
java.lang.NullPointerException
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:541)
at org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:555)
at rest.BookServiceTest.get(BookServiceTest.java:21)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
// ...
Process finished with exit code -1
有什么区别?有人知道为什么它使用静态的内部类,而不使用外部类吗
# 1 楼答案
我弄明白了——我用错了进口
它应该是
import org.junit.Test
,而不是import org.junit.jupiter.api.Test