2011-07-20 90 views
0

我正在使用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(..);   
} 

怎么能嘲笑我在测试中的合作者?

回答

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

或者您可以使用testfun-JEE为您的测试中运行一个轻量级的JAX-RS(基于RestEasy的和TJWS),并使用testfun-JEE的JaxRsServer JUnit的规则构建REST工作对我来说请求并主张答复。

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