Using Jersey Test Framework to target APIs in other files

310 Views Asked by At

I have read the documentation concerning the Jersey Test framework and have successfully used JerseyTest's target method to reach a @Path annotated endpoint within my own file. Simplified code is below.

public class TestApplication extends ResourceConfig {
    public TestApplication() {
        registerClasses(TestService.class);
    }
}

@Override
protected Application configure() {
    return new TestApplication();
}

@Path("create")
public static class TestService {
    @POST
    @Path("testObj")
    @Consumes(APPLICATION_JSON)
    public static Response createTestObj(final TestObj testObj) {
        return Response.ok("testObj created").build();
    }
}

@Test
private void ensureObjectCreated() {
    JSONObject myObj = createNewObj();
    final Response response = target("create/testObj").request(APPLICATION_JSON)
                              .post(Entity.json(myObj.toString()));
    Assert.isEqual(response.status, 200);
}

Now I want to reach a @Path annotated endpoint in other files/directories. How do I do so? The problem may be that the other files are actual production code, so I cannot make the classes static. However the endpoints in the other paths are reachable.

1

There are 1 best solutions below

1
On BEST ANSWER

Just register them in the resource config, either individually (depending on the scope of the test), or specify a package to scan with the packages method.

@Override
public ResourceConfig configure() {
    return new ResourceConfig()
        .register(SomeResource.class)
        .packages("your.resource.package.to.scan");
}

The only reason the class in the example is static is because it is an inner class that needs to be instantiated by the framework.

When you access the resource, it will not include the root application path, only the @Path value on the class, and whatever sub path, just like in your code above.