【问题标题】:Test two sequential okhttp calls with junit使用 junit 测试两个连续的 okhttp 调用
【发布时间】:2018-10-16 09:16:33
【问题描述】:

我有一个公共方法:

public class methodUnderTest() {
     A();
     B();
}

还有两个私有方法:

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

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

我想测试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);

【问题讨论】:

    标签: java junit mockito


    【解决方案1】:

    您可以将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);
    

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

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2019-06-24
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      相关资源
      最近更新 更多