Resteasy Server-side Mock Framework

岁酱吖の 提交于 2019-12-08 10:44:21

问题


I am using Resteasy serverside mock framework to test my service. I dont want to test business logic but I would like test the data produced by the service.

Using this approach I am able to create a simple test. However, in my RestEasy service I have a few dependency which I would like to mock.

See the following example service which I would like test. The collaborator must be mocked so the service can be tested.

@Path("v1")
Class ExampleService {
    @inject
    private Collaborator collaborator;

    @GET
    @Path("/")
    @Produces({ "application/xml", "application/json" })
    public Response getDummy() throws WSAccessException, JsonParseException,    JsonMappingException, IOException {

        ...
        Result result = collaborator.getResult();
        ..
        return Response.ok("helloworld").build();
    }
}

The junit test is the following

@Test
public void testfetchHistory() throws URISyntaxException {
    Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
    POJOResourceFactory noDefaults = new POJOResourceFactory(ExampleService.class);
    dispatcher.getRegistry().addResourceFactory(noDefaults);
    MockHttpRequest request = MockHttpRequest.get("v1/");
    MockHttpResponse response = new MockHttpResponse();

    dispatcher.invoke(request, response);


    Assert.assertEquals(..);         
}

How can I mock the collaborator in the test?


回答1:


This worked for me using EasyMock

    @Test
public void testfetchHistory() throws URISyntaxException {

    Collaborator mockCollaborator  = EasyMock.createMock(Collaborator.class);
    Result result = new Result();
    EasyMock.expect(mockCollaborator.getResult()).andReturn(result);
    EasyMock.replay(mockCollaborator);

    ExampleService obj = new ExampleService();
    obj.setCollaborator(mockCollaborator);

    Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
    dispatcher.getRegistry().addSingletonResource(obj);
    MockHttpRequest request = MockHttpRequest.get("v1/");
    MockHttpResponse response = new MockHttpResponse();

    dispatcher.invoke(request, response);

    Assert.assertEquals(..); 

    EasyMock.verify(mockCollaborator);       
}



回答2:


Alternatively you can use testfun-JEE for running a lightweight JAX-RS (based on RESTeasy and TJWS) inside your test and using testfun-JEE's JaxRsServer junit rule for building REST requests and asserting the responses.

testfun-JEE supports injection of other EJBs as well as mock objects into your JAX-RS resource class.



来源:https://stackoverflow.com/questions/6761144/resteasy-server-side-mock-framework

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