2011-07-20 88 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資源類中。