问题
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