[英]Optimization of rest-assured and gson at rest test with java with cucumber
我有一個rest api,它返回此嵌套響應:
"latitude":37.8267,
"longitude":-122.4233,
"timezone":"America/Los_Angeles",
"minutely":{
"summary":"Clear for the hour.",
"icon":"clear-day",
"data":[
{
"time":1517431560,
"precipIntensity":0,
"precipProbability":0
},
{
"time":1517431620,
"precipIntensity":0,
"precipProbability":0
},
....
因此,我需要獲取詳細的天氣預報並將其放在對象上。 我在getter和setters(未列出)上進行了HourlyWeather課程:
public class HourlyWeather {
String time;
String precipIntensity;
String precipProbability;
這是我用java實現的黃瓜步驟:
@Given("^rest api$")
public void restApi() throws Throwable {
restApiUrl = "https://api.darksky.net/forecast/******"; // my api key
}
@And("^rest api parameters$")
public void restApiParameters() throws Throwable {
restApiUrl = restApiUrl + "/37.8267,-122.4233";
}
@When("^I \"([^\"]*)\" rest api execution result$")
public void iRestApiExecutionResult(String method) throws Throwable {
RestAssured.baseURI = restApiUrl;
RequestSpecification httpRequest = RestAssured.given(); response = httpRequest.request(Method.GET);
}
這是我的問題:我在這里使用放心的方式來獲取嵌套JSON的一部分(我需要)。 我在這里進行toString轉換。 之后-我使用GSON反序列化我的字符串,並創建一個帶有所有每小時天氣json密鑰數據的HourlyWeather []對象。 有什么辦法可以避免這種轉換並簡化我的代碼?
@Then("^I should deserialize result just to know how to do that$")
public void iShouldDeserializeResultJustToKnowHowToDoThat() throws Throwable {
// get only part of my nested json
// I would like ot get this part as an array list of HourlyWeather.class objects, not
// as ArrayList of HashMaps, so this is String here
String stringOfRequiredJSON = response.jsonPath().getJsonObject("minutely.data").toString();
Gson gson = new Gson();
HourlyWeather[] hourlyWeatherForecast = gson.fromJson(stringOfRequiredJSON, HourlyWeather[].class);
printHourlyWeather(hourlyWeatherForecast);
}
謝謝!
是的,如果您願意切換到其他工具,則必須評估空手道,它將使您擺脫使用Java中的JSON的困擾,這讓我們所有人都承認-這不是使用JSON的最佳語言。
我還想指出我的詳細答案,以了解為什么嘗試使用BDD進行REST API測試不是您的最佳選擇: https : //stackoverflow.com/a/47799207/143475
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.