Resteasy服务器端模拟框架

时间:2011-07-20 11:27:34

标签: unit-testing junit jax-rs resteasy

我正在使用Resteasy服务器端模拟框架来测试我的服务。我不想测试业务逻辑,但我想测试服务生成的数据。

使用this方法,我可以创建一个简单的测试。但是,在我的RestEasy服务中,我有一些依赖,我想嘲笑。

请参阅以下我要测试的示例服务。必须嘲笑协作者,以便测试服务。

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

junit测试如下

@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(..);         
}

如何在测试中模仿协作者?

2 个答案:

答案 0 :(得分:5)

这对我来说使用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);       
}

答案 1 :(得分:0)

或者,您可以使用testfun-JEE在测试中运行轻量级JAX-RS(基于RESTeasy和TJWS),并使用testfun-JEE的JaxRsServer junit规则来构建REST请求并声明响应。

testfun-JEE支持将其他EJB以及模拟对象注入到JAX-RS资源类中。