Java 如何模拟JUnit测试的okhttp响应
我正在通过okhttp向第三方API发出出站HTTP请求:Java 如何模拟JUnit测试的okhttp响应,java,unit-testing,mockito,okhttp,mockwebserver,Java,Unit Testing,Mockito,Okhttp,Mockwebserver,我正在通过okhttp向第三方API发出出站HTTP请求: public @Nullable result Call3rdParty { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS) .readTimeout(RW_TIMEOUT, TimeUnit.MILLISECONDS)
public @Nullable result Call3rdParty {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(RW_TIMEOUT, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
//Deserialize and do minor data manipulation...
}
我想创建一个单元测试并模拟响应
private MockWebServer server;
@Before
public void setUp() throws IOException {
this.server = new MockWebServer();
this.server.start();
}
@After
public void tearDown() throws IOException {
this.server.shutdown();
}
@Test
public void Test_SUCCESS() throws Exception {
String json = readFileAsString(file);
this.server.enqueue(new MockResponse().setResponseCode(200).setBody(json));
//TODO: What to do here??
}
模拟响应进入队列后,我需要做什么来返回模拟响应并在我正在测试的方法的剩余部分中使用它?项目文档介绍了这一点
问题中的代码不完整,有数百个在线教程等提供了答案。@YuriSchimke请在此处提及其中一个,以供参考。随机的,很难知道给出了什么最好的代码。有很多不同的方法来实现此测试或实现此测试的目标
// Ask the server for its URL. You'll need this to make HTTP requests.
HttpUrl url = server.url("/myendpoint");
// Call your client code here, passing the server location to it
response = Call3rdParty(url)