So I have tested it with this example:
Path: 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);
}
}
This is the output of the test:
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
But when I put the REST service class at in the main package, it doesnt work anymore (NullPointerException):
Package: pkg > src > main > java > rest > BookService
@Path("books")
public class BookService {
@GET
public String getAll() {
return "test";
}
}
And then the Test:
Package: 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();
}
}
This is the output of the test:
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
What is the difference? Does anyone have a clue, why it works with a static inner class, but not with a external one?
Figured it out - I used the wrong import.
Instead of
import org.junit.jupiter.api.Test
it should beimport org.junit.Test
.