Bry*_*yan 5 java unit-testing mockito okhttp mockwebserver
我正在通过 okhttp 向第 3 方 API 发出出站 HTTP 请求:
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...
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个单元测试并模拟响应。
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??
}
Run Code Online (Sandbox Code Playgroud)
模拟响应入队后,我需要做什么才能返回模拟响应并在我正在测试的方法的其余部分中使用它?
项目文档涵盖了这一点
https://github.com/square/okhttp/tree/master/mockwebserver
// 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8217 次 |
| 最近记录: |