2012-05-15 53 views
1

我正在嘗試爲RESTeasy Web服務編寫JUnit測試用例。我想爲此使用RESTeasy MockDispatcherFactory,並不依賴於任何數據訪問層。帶有模擬數據層的JUnit RESTeasy服務......我該如何嘲笑它?

在我以前的測試案例的創作中,我用的Mockito嘲笑數據訪問,但我有麻煩RestEasy的的MockDispatcherFactory這樣做......

服務類:

import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 

@Path("") 
public class Service { 
private StubDao stubDao; 
    public Service(){ 
     this.stubDao = new StubDao(); 
    } 

    public Service (StubDao stubDao){ 
     this.stubDao = stubDao; 
    } 

    @GET 
    @Produces(MediaType.TEXT_HTML) 
    public String get(){ 
     return stubDao.getTheValue(); 
    } 
} 

數據訪問:

public class StubDao { 
    private String value; 

    public StubDao(){ 

    } 

    public String getTheValue(){ 
     //Stubbed Data Access 
     return value; 
    } 

    public void setTheValue(String v){ 
     this.value = v; 
    } 
} 

單元測試:

import java.net.URISyntaxException; 

import junit.framework.Assert; 

import org.jboss.resteasy.core.Dispatcher; 
import org.jboss.resteasy.mock.MockDispatcherFactory; 
import org.jboss.resteasy.mock.MockHttpRequest; 
import org.jboss.resteasy.mock.MockHttpResponse; 
import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory; 
import org.junit.Test; 


public class TestService { 
@Test 
public void testService() throws URISyntaxException{ 

     POJOResourceFactory factory = new POJOResourceFactory(Service.class); 
    //I Need to use Mockito to mock the StubDao object!!!  

    Dispatcher dispatcher = MockDispatcherFactory.createDispatcher(); 
    dispatcher.getRegistry().addResourceFactory(factory); 

     MockHttpRequest request = MockHttpRequest.get(""); 
    MockHttpResponse response = new MockHttpResponse(); 

    //here my exception is thrown 
    dispatcher.invoke(request, response); 

    System.out.println(response.getContentAsString()); 

    // but I expect the response to be 404 (which works outside the mock setup  
    Assert.assertEquals(response.getStatus(), 404); 
} 
} 

通常我會使用的Mockito嘲笑像這樣的數據訪問:

設置模擬

@Before 
public void setup() { 
    StubDao stubDao = new StubDao(); 
} 

定義模擬

when(stubDao.getTheValue()).thenReturn("the mocked value"); 

然而,RestEasy的的嘲諷創建一個新的實例內部的服務類。我的問題是,如何將模擬數據訪問插入到服務的構造函數中?

任何幫助表示讚賞!

回答

4

找到了答案感謝另一個帖子(Resteasy Server-side Mock Framework

使用下面讓我來創建服務類的實例,並設置數據訪問:

dispatcher.getRegistry().addSingletonResource(svc); 

相反的:

dispatcher.getRegistry().addResourceFactory(factory); 
1

或者,您可以使用testfun-JEE在測試中運行輕量級JAX-RS(基於RESTeasy和TJWS),並使用testfun-JEE JaxRsServer junit規則,用於構建REST請求並聲明響應。

testfun-JEE支持將其他EJB以及mockito模擬對象注入到JAX-RS資源類中。