可以这么说,我正在调用第三方端点。我只是调用端点并解析响应。
public ListUsers listUsers() {
String url = "/api/v1/account/?apikey=" + apiKey;
String signature = null;
try {
signature = generateSignature(url);
} catch (SignatureException e) {
e.printStackTrace();
}
Call newCall = apiCall("GET", url, signature, null);
Type localVarReturnType = new TypeToken<ListUsers>() { }.getType();
ApiResponse<ListUsers> responseFromApiClient = apiClient.execute(newCall, localVarReturnType);
return responseFromApiClient.getData();
}
listUsers() 函数已被重构以获得更好的抽象
public ListUsers listUsers() {
String url = "/api/v1/account/?apikey=" + apiKey;
Type localVarReturnType = new TypeToken<ListUsers>() { }.getType();
ApiResponse<ListUsers> responseFromApiClient = apiClient.execute(buildApiCall("GET", url, null), localVarReturnType);
return responseFromApiClient.getData();
}
这个特定的端点不接受任何主体,并返回我随后解析的 json。
{
"meta": {
"limit": 0,
"offset": 0,
"total_count": 1
},
"objects": [
{
"address_one": "",
"address_three": "",
"address_two": "",
"country_code": "",
"cs_domain_id": null,
"date_joined": "2019-07-05T13:50:21",
"disable_personal_account": false,
"email": "noreply@some.com",
"first_name": "",
"id": 1,
"is_reseller": true,
"is_superuser": true,
"is_verified": true,
"last_login": null,
"last_name": "",
"paywall": true,
"postal_code": "",
"projects": [],
"reference_number": "",
"reseller_id": 1,
"reseller_name": "ROOT",
"reseller_rights": [
{
"domain_id": null,
"id": 1,
"level": "owner",
"name": "ROOT"
}
],
"resource_uri": "/api/v1/account/1/",
"saml": false,
"state": 0,
"status": "enabled",
"surname": "",
"username": "admin",
"uuid": "1c208540-3ed9-4741-a936-a574a3ded12a"
}
]
}
然后这个 json 响应被解析。
如何为此编写适当的单元测试,或者是否不需要?我想出的唯一测试只是一个基本测试,我实际调用该服务,但至于纯单元测试,它不会在我的构建服务器上运行。这是测试
@Test
void getListProjectsTest() {
GqConsoleApiClient gcac = new GqConsoleApiClient();
ListProjects response = gcac.listProjects();
System.out.println(listProjects);
Assert.assertEquals(20, response.getMeta().getLimit());
Assert.assertEquals("some-customer-id", response.getObjects().get(0).getCustomerId());
}
最佳答案
有多种方法可以做到这一点。如果我是你,我会这样做
首先创建一个包含正确响应的 json 文件
写一个测试用例
2.1。在测试类中加载json文件
File sampleFile = new File(URLDecoder.decode(classLoader.getResource("jsonFilePath").getFile(), "UTF-8"));
2.2 将此文件转换成java类型,由第三方API返回。在你的情况下是
ApiResponse<ListUsers>
.为此,您可以使用 Jackson 或 Gson 库2.3 你应该创建一个 apiClient 类型的 mock 并模拟
execute
称呼。并返回步骤2.2得到的java对象。像这样的东西when(apiClient.execute(any(), any()).thenReturn(....)
2.4 编写断言检查java对象的各个方面
通过这种方式,您可以轻松创建多个 json 文件来测试来自 api 的各种响应。
关于java - 来自第三方 API 的模拟调用和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58186374/