【问题标题】:Optimization of rest-assured and gson at rest test with java with cucumberjava with cucumber 优化rest-assured和gson at rest测试
【发布时间】:2018-01-31 21:02:15
【问题描述】:

我得到了一个 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 和 setter(未列出)制作了一个 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 gson rest-assured


    【解决方案1】:

    是的,如果您愿意切换到其他工具,则必须评估 Karate 它使您不必在 Java 中与 JSON 作斗争,这让我们都承认 - 这不是使用 JSON 的最佳语言。

    我还想指出我的详细回答,说明为什么尝试使用 BDD 进行 REST API 测试不是最好的利用时间:https://stackoverflow.com/a/47799207/143475

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2016-04-11
      • 2020-07-16
      • 2019-11-20
      • 2016-05-06
      • 1970-01-01
      相关资源
      最近更新 更多