使用 selenium Webdriver 在 Java 中读取 JSON 文件并写入 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37575632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:37:47  来源:igfitidea点击:

Reading JSON file and Writing into a JSON file in Java using selenium Webdriver

javajsonselenium

提问by sam Hymanson

I am working on an Automation Framework and I am looking for an alternative for excel to store test data, element locators and page objects.

我正在研究自动化框架,并且正在寻找 excel 的替代方案来存储测试数据、元素定位器和页面对象。

So one my friend working on Automation is using json file to store all data as its easy and faster in reading and writing data, Also it can be easy in maintaining. They are using ruby as the language.

所以我的一位从事自动化工作的朋友正在使用 json 文件来存储所有数据,因为它可以轻松快速地读取和写入数据,并且易于维护。他们使用 ruby​​ 作为语言。

So I wanted to know if we can do the same using java & selenium to achieve this?

所以我想知道我们是否可以使用 java & selenium 来做到这一点?

I have searched google for this and it looks like there is a library called "gson" from google, but none that shows how to use it using selenium.

我已经在谷歌上搜索过这个,看起来谷歌有一个名为“gson”的库,但没有一个显示如何使用硒来使用它。

please share your thoughts on this.

请分享您对此的看法。

Thank you!!

谢谢!!

回答by pyde

I can't speak to including element locators in a JSON file, as I follow the page object model and include all those in the java classes. However, reading test data from a JSON file is very easy. It's been a while since I've messed around with this, but I used JSON Simple(which I still use to generate JSON objects/files) and did something like this to read in the file:

我不能说在 JSON 文件中包含元素定位器,因为我遵循页面对象模型并将所有这些都包含在 java 类中。但是,从 JSON 文件中读取测试数据非常容易。自从我弄乱这个已经有一段时间了,但我使用了JSON Simple(我仍然使用它来生成 JSON 对象/文件)并执行类似的操作来读取文件:

protected JSONObject getDataFile(String dataFileName) {
    String dataFilePath = "src/test/resources/";
    JSONObject testObject = null; 

    try {
        FileReader reader = new FileReader(dataFilePath + dataFileName);                        
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        testObject = (JSONObject) jsonObject;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return testObject;
}

Once you have the JSON Object, JSON simple provides a few different ways to interact with it and get the values. I've played around with Gson a while back and I think that was fairly similar.

拥有 JSON 对象后,JSON simple 提供了几种不同的方式与其交互并获取值。不久前我和 Gson 一起玩过,我认为这非常相似。

I don't know how your data file is/will be structured, but I had a key string that represented a test case name, and the value was a json object that contained other key-value pairs with the actual data and I fed that data to a TestNG data provider. If that is similar to your setup, I can share that code.

我不知道你的数据文件是如何/将如何结构的,但我有一个表示测试用例名称的键字符串,该值是一个 json 对象,其中包含其他键值对和实际数据,我输入了它数据到 TestNG 数据提供者。如果这与您的设置类似,我可以分享该代码。

EDIT: Here is the method used by the @DataProvider

编辑:这是@DataProvider 使用的方法

public Object[][] getTestScenarios(String dataFileName, String testCaseName) {
    JSONArray testCase = (JSONArray) getDataFile(dataFileName).get(testCaseName);
    List<JSONObject> testScenarioArray = new ArrayList<JSONObject>();

    for (int i = 0; i < testCase.size(); i++) {
         testScenarioArray.add((JSONObject) testCase.get(i));
    }

    Object[][] dataProviderArray = new Object[testScenarioArray.size()][];
    for (int scenario = 0; scenario < testScenarioArray.size(); scenario++) {
        String scenarioName = null;

        if ((String) testScenarioArray.get(scenario).get("scenario") != null) {
            scenarioName = (String) testScenarioArray.get(scenario).get("scenario");
        } else {
            scenarioName = "No scenario name specified";
        };
        dataProviderArray[scenario] = new Object[] { scenarioName, (JSONObject) testScenarioArray.get(scenario) };
    }
    return dataProviderArray;
}

The scenario name stuff could be removed, as I believe I only used that for logging or reporting, if I recall correctly. The reason I had it as a JSONArray and coded in this fashion is so a single test case could have an array with multiple scenarios with differing data. Didn't want the tests to have to care how many scenarios there were.

如果我没记错的话,场景名称的东西可以被删除,因为我相信我只将它用于日志记录或报告。我将它作为 JSONArray 并以这种方式编码的原因是,单个测试用例可以有一个数组,其中包含具有不同数据的多个场景。不希望测试必须关心有多少场景。

回答by Vasudha

I have read a JSON Array from DB and made a list of a JSON object from JSON Array.

我从数据库中读取了一个 JSON 数组,并从 JSON 数组中创建了一个 JSON 对象列表。

The array looks as follows:

该数组如下所示:

[{
    "index": "data",
    "type": "message",
    "sum": 
    {
        "message": "HELLO",
    },
}, {
    "index": "data",
    "type": "message",
    "sum":
    {
        "message": "HELLO123",
    }
}]

It is collected from DB in STRING form but is an array as it has SQUARE BRACKETS: [{Json1}, {Json2}].

它以 STRING 形式从 DB 收集,但它是一个数组,因为它具有 SQUARE BRACKETS: [{Json1}, {Json2}]

String data = "ArrayFromDB";
JSONArray jsonArr = new JSONArray(data);
List<String> listJSON = new ArrayList<String>();

for (int i = 0; i < jsonArr.length(); i++)
{
    listSMSJSON.add(jsonArr.getJSONObject(i).getJSONObject("sum").getString("message"));
}

System.out.println(listJSON);

listJSON is printed as [HELLO, HELLO123]

listJSON 打印为 [HELLO, HELLO123]