2017-01-22 502 views
0

我正在嘗試使用Mockito來模擬JUnit測試的方法。該方法從simple-json獲取JSONObject作爲參數,並用JSONObject進行響應。我試圖模擬的方法來自另一個類,我正在測試的代碼調用它。我似乎無法讓Mockito趕上我的請求並作出相應的迴應。我完全錯過了什麼嗎?以JSONObject作爲Mockito模擬方法中的參數

public class TestClass{ 
    JSONObject jsonRequest; 
    JSONObject jsonReturn; 

    AnotherClass anotherClass = Mockito.mock(AnotherClass.class); 

    @Before 
    public void setUp(){ 
    jsonRequest = this.readJSONFromFile("jsonRequest.json"); 
    jsonReturn = this.readJSONFromFile("jsonReturn.json"); 
    Mockito.when(anotherClass.anotherClassMethod(jsonRequest)).thenReturn(jsonReturn); 
    } 

    @Test 
    public void testMethod(){ 
    TestClass testClass = new TestClass(); 
    assertEquals(testClass.method(jsonRequest), jsonReturn); 
    } 
} 
+0

所以我試圖寫出一個例子,並失敗了。我現在已經對我的例子進行了修改並將其付諸實踐: – JimBob91

回答

0

我想你錯了

assertEquals(testClass.method(jsonRequest), jsonReturn); 
1

你嘲笑的模擬對象, ,但在測試類中的方法斷言,而不是使用模擬對象testClass, 你實例化一個新的TestClass對象不會被Mockito攔截。 加上你的代碼的最後一行看起來不正確,

assertEquals(testClass.method(jsonRequest, jsonReturn)); 

確定。您的testMethod應該如下所示:

@Test 
public void testMethod(){ 
    assertEquals(testClass.method(jsonRequest), jsonReturn); 
} 

希望這有助於您。

+0

@ JimBob91:我認爲你對嘲笑感到困惑。 Mockito只會在您的請求/方法被mock(模擬對象)調用/發出時纔會捕獲您的請求/方法。在你的代碼中,你所擁有的唯一模擬對象是「anotherClass」,並且你在你的'@ Before'方法中嘲笑了它的anotherClassMethod(),這意味着Mockito會捕獲你的請求,只有當你調用anotherClass.anotherClassMethod(jsonRequest)方法在你的'@ Test'方法中。 –

+0

而在你的'testMethod()'你調用'testClass.method(jsonRequest)','testClass'不是一個模擬,你不會模擬'testClass.method(jsonRequest)'行爲,所以Mockito不會捕獲它。 –

0

你在嘲笑錯誤的方法簽名。你有一個模擬設置爲method(JSONObject),但調用method(JSONObject, JSONObject)(注意兩個參數)。您將需要模擬雙參數方法,或者只在測試中調用單參數方法。

我也建議改變模擬接受的JSONObject任何實例:

Mockito.when(testClass.method(any(JSONObject.class)).thenReturn(jsonReturn); 

最後,如Mehmudjan穆罕默德提到,從測試中刪除的TestClass新實例,否則你嘲笑贏得」工作。您應該使用在測試頂部聲明的實例。

相關問題