繁体   English   中英

带有Java的黄瓜的安心测试和GSON静止测试的优化

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM