Unit Testing with Jersey Rest Test Framework and Mockito

时光毁灭记忆、已成空白 提交于 2019-12-04 01:54:26

问题


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);
    }
}

回答1:


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));


来源:https://stackoverflow.com/questions/42062506/unit-testing-with-jersey-rest-test-framework-and-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!