首页 文章

Selenium Web Driver Eclipse:从json文件或xml文件传递用户名和密码

提问于
浏览
0

我需要测试具有多个用户名和密码的登录页面,并且需要从JSON文件或XML文件传递用户名和密码 . 有没有办法实现它?

driver.findElement(By.id( “用户名”))的SendKeys(用户名) . driver.findElement(By.id( “密码”))的SendKeys(密码) .

我应该如何在selenium web驱动程序中引用sendkeys函数中的值

1 回答

  • 0

    以下答案基于JSON格式低于以下的假设:

    {
        "testData": [{
            "userName": "test1",
            "password": "password1"
        }, {
            "userName": "test2",
            "password": "password2"
        }]
    }
    

    我建议使用Jackson来反序列化数据 . 您需要在类路径中使用相同版本的jackson-core,jackson-annotations,jackson-databind jar .

    创建类用户如下:

    public class User {
        private String userName;
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        private String password;
    }
    

    创建类TestData如下:

    public class TestData {
        List<User> testData;
    
        public List<User> getTestData() {
            return testData;
        }
    
        public void setTestData(List<User> testData) {
            this.testData = testData;
        }
    }
    

    反序列化将按如下方式进行:

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
            WebDriver driver = new ChromeDriver();
            // You can read the json from property file/service call and store to string.
            String jsonString = "{\"testData\": [{\"userName\": \"test1\",\"password\": \"pwd1\"}, {\"userName\": \"test2\", \"password\": \"pwd2\" }]}";
            ObjectMapper mapper = new ObjectMapper();
            TestData obj = mapper.readValue(jsonString,TestData.class);
            for (User data : obj.getTestData()) {
                 driver.findElement(By.id("usernameS")).sendKeys(data.getUserName());
                 driver.findElement(By.id("passwordS")).sendKeys(data.getPassword());
            }
    }
    

相关问题