gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:44:05 25 4
gpt4 key购买 nike

我有一个公共(public)方法:

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

和两个私有(private)方法:

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

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

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

//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);

最佳答案

您可以为您的call.execute()

链接 thenReturn
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。

关于java - 使用 junit 测试两个连续的 okhttp 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52832005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com