使用 junit 测试两个连续的 okhttp 调用

bra*_*and 3 java junit mockito

我有一个公共方法:

public class methodUnderTest() {
     A();
     B();
}
Run Code Online (Sandbox Code Playgroud)

和两个私有方法:

private class A() {
     ...
     okHttpClient.newCall(request).execute();
     ...
}

private class B() {
     ...
     okHttpClient.newCall(request).execute();
     ...
}
Run Code Online (Sandbox Code Playgroud)

我想测试该方法,methodUnderTest但我不知道如何模拟 okHttp 调用。我已经模拟了第一个调用(来自 A 类)及其响应,但会被来自 B 类的第二个调用覆盖(例如,来自 A 类的调用的响应将是来自 B 类的响应响应)。可以区分每个类的调用吗?

//inside the test method [with pesudocode]:
// for class A
ResponseA = response.body({"id":"1"});
when(call.execute()).thenReturn(response1);                               
when(okkHttpClient.newCall(any(Request.class))).thenReturn(call);

// for class B
ResponseB = response.body({"type"="car"});
when(call.execute()).thenReturn(responseB);               
when(okkHttpClient.newCall(any(Request.class))).thenReturn(call);
Run Code Online (Sandbox Code Playgroud)

Ale*_*kin 6

你可以thenReturn为你的链call.execute()

Response responseA = ;
Response responseB = ;

OkHttpClient okHttpClient = mock(OkHttpClient.class);
Call call = mock(Call.class);

when(call.execute()).thenReturn(responseA).thenReturn(responseB);
when(okHttpClient.newCall(any(Request.class))).thenReturn(call);
Run Code Online (Sandbox Code Playgroud)

现在,您的模拟调用应该在第一次调用时返回 responseA,在其他调用时返回 responseB。