【发布时间】:2017-07-10 10:29:09
【问题描述】:
我有一个 API POST 端点,它返回一个结构如下的 json 对象:
- 数据(我发过来的原始数据)
- JsonAPI(端点符合的 JSON API 版本)
- 状态(对端点的调用状态)
- 消息(在架构验证错误的情况下使用)
所有这些都使用 GSON fromJson() 存储在以下 POJO 中:
package json.responses;
import com.google.gson.JsonElement;
public class SupplierResponseTest {
private StatusResponse status;
private JsonElement jsonapi;
private String message;
private JsonElement data;
public SupplierResponseTest(StatusResponse status, JsonElement jsonapi) {
this.status = status;
this.jsonapi = jsonapi;
}
public SupplierResponseTest(StatusResponse status, JsonElement jsonapi, String message) {
this.status = status;
this.jsonapi = jsonapi;
this.message = message;
}
public SupplierResponseTest(StatusResponse status, JsonElement jsonapi, JsonElement data) {
this.status = status;
this.jsonapi = jsonapi;
this.data = data;
}
public StatusResponse getStatus() {
return status;
}
public JsonElement getJsonapi() {
return jsonapi;
}
public String getMessage() {
return message;
}
public JsonElement getData() {
return data;
}
}
如您所见,我目前将 jsonapi 值存储为 JsonElement。这意味着当我从 json 解析值时,我最终得到的字符串值为 {"version":"1.0"}。
我的目标是将此值存储为子(?)对象。并且,与其将 api 值作为 SupplierResponseTest 中的 JsonElement,不如将其作为对象或枚举。但是,我不知道如何做到这一点。
以这种方式存储值的目的是能够对新对象的值(1.0)执行黄瓜验证,而不是解析一堆 json {"version":"1.0"}。
我用的黄瓜是:
Scenario Outline: Add Supplier Details
Given the system does not know about any Suppliers
When the client adds the following <supplier>
Then the response status is <status>
And the response has the <jsonapi> version
And the response has the request <supplier>
Examples:
| supplier | status | jsonapi |
| "Blue Network Energy LTD" | "SUCCESS" | "1.0" |
我遇到问题的具体步骤定义是:
@Then("^the response has the \"([^\"]*)\" version$")
public void the_response_has_the_version(String arg1) throws Throwable {
try{
//This returns a string of json...
JsonElement apiVersion = supplierResponse.getJsonapi();
//The below attempts to assert the two values "1.0" and {"version":"1.0"}
Assert.assertEquals(arg1, apiVersion.toString());
} catch (Exception e){
System.out.println(e.getMessage());
}
}
【问题讨论】:
标签: java json gson cucumber pojo