Search code examples
javarestunit-testingjerseyjersey-test-framework

Unit Testing with Jersey Rest Test Framework and Mockito


Could someone help me on this. I am writing Unit test for Rest resource using Jersey rest test framework version 2.21.(On Grizzly container).

When I debug the test class, am seeing mock object for myManager . But when the debug enters my "MyResouce class, myManager object is becoming null and getting NullPointer Exception.

Have tried with solutions given by different people, but no luck.Could someone help me please. Am with this problem from almost three days. :(

My Resource class is like this.

@Component
@Path("/somepath")
public class MyResource {
    @Autowired
    private MyManager myManager;

    @Path("/somepath")
    @GET
    @Produces("application/json")
    @ResponseType(String.class)
    public Response getResults(@QueryParam("queryParam") String number) {
        // myManager is an interface
        String str = myManager.getResult(number);
    }
}

And here is my testclass

public class MyResourceTest extends JerseyTest {
    @Mock
    private MyManager myManager;

    @InjectMocks
    private MyResource myResource;

    @Override
    protected Application configure() {
        MockitoAnnotations.initMocks(this);
        return new ResourceConfig().register(MyResource.class)
                .register(new AbstractBinder() {
                    @Override
                    protected void configure() {
                        bind(myManager).to(MyManager.class);
                    }
                });
    }

    @Test
    public void getResultsTest() {
        when(myManager.getResult(anyString())).thenReturn(mock(String.class));
        String str = target("path").queryParam("queryParam","10").request().get(String.class);
    }
}

Solution

  • You're using Spring (injection) annotations, so the service will be looked up from the spring context. That's why it's null, because you haven't set up the mock in the spring context.

    The best thing to do is to use constructor injection (instead of field injection). This makes testing a lot easier

    @Path(..)
    public class MyResource {
        private final MyManager manager;
    
        @Autowired
        public MyResource(MyManager manager) {
            this.manager = manager;
        }
    }
    

    Then in your test

    return new ResourceConfig()
        .register(new MyResource(myManager));