2013-07-30 146 views
1

我想知道我應該如何去注入一個模擬 - 我們有一堆做服務器調用的類,但是我們的CI系統不能訪問外部資源,因此不會訪問服務器。因此,必須模擬調用,並且需要返回硬編碼值(例如響應代碼)。mockito和powermocks注入模擬

所以,這裏的代碼片段:

HttpPost httpRequest = new HttPost(uri); 
    //some code here 
    try{ 
     httpRequest.setEntity(entity); 
     HttpResponse response = httpClient.execute(httpRequest); 
     ... 
    //other, irrelevant, code is here 

那麼,是不是可以注入模擬成httpClient.execute(HttpRequest的),並從測試單元返回硬編碼的響應實體?

謝謝

+0

這可能有所幫助。 http://johannesbrodwall.com/2009/10/24/testing-servlets-with-mockito/ – UpAllNight

回答

2

通常嘲諷某些物體看起來是這樣的:

public class TestClass { 

    private HttpServer server; 

    public HttpServer getServer() { 
     return server; 
    } 

    public void setServer(HttpServer server) { 
     this.server = server; 
    } 

    public void method(){ 
     //some action with server 
    } 
} 

和測試類:

public class TestClassTest { 
    //class under test 
    TestClass test = new TestClass(); 

    @org.junit.Test 
    public void testMethod() throws Exception { 
     HttpServer mockServer = Mockito.mock(HttpServer.class); 
     test.setServer(mockServer); 
     //set up mock, test and verify 
    } 
} 

在這裏你一些有用的鏈接: