2017-01-22 46 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新实例,否则你嘲笑赢得”工作。您应该使用在测试顶部声明的实例。

相关问题