开发者

Unit testing Jersey Resources with Guice injected fields

开发者 https://www.devze.com 2023-04-11 14:57 出处:网络
I have a Jersey Resource that I want to test with JUnit. The resource uses Guice Providers to inject certain fields:

I have a Jersey Resource that I want to test with JUnit. The resource uses Guice Providers to inject certain fields:

@Path("/example/")
class ExampleResource {
    @Inject
    Provider<ExampleActionHandler> getMyExampleActionHandlerProvider;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<ExamplePojo> getExampleList() {
        ExampleActionHandler handler = getMyExampleActionHandlerProvider.get();
        han开发者_如何转开发dler.doSomething();
    ...

This all works beautifully when using a real server to serve the API, however testing it is problematic.

My test class currently looks something like:

public class ApiTest extends JerseyTest {

  public ApiTest() throws Exception {
    super();
    ApplicationDescriptor appDescriptor = new ApplicationDescriptor();
    appDescriptor.setContextPath("/api");
    appDescriptor.setRootResourcePackageName("com.my.package.name");
    super.setupTestEnvironment(appDescriptor);
  }

  @Test
  public void testHelloWorld() throws Exception {
    String responseMsg = webResource.path("example/").get(String.class);
    Assert.assertEquals("{}", responseMsg);
  }
}

Clearly, Guice isn't getting the opportunity to initialize the fields in ExampleResource so that the handler.doSomething() call doesn't result in a NullPointerException.

Is there a way to tell Jersey to instantiate the ExampleResource class using Guice so that the Provider works?


One way to do it is to break the tests to few steps. You need to create the injector you're configuring the service with and test that injector (see Testing Guice Servlet bindings and Testing Guice can init servlets). Using these tests you make sure you have the right bindings in place. Once you have the injector, get the ApplicationDescriptor object from it with

ExampleResource exampleResource = injector.getInstance(ExampleResource.class);
Assert.assertEquals(myList, getExampleList());
0

精彩评论

暂无评论...
验证码 换一张
取 消