【问题标题】:java match string to variable name and pass the variable's valuejava将字符串匹配到变量名并传递变量的值
【发布时间】:2023-03-08 20:06:01
【问题描述】:

我是 Cucumber Selenium 的初学者,使用 Java 并已通过 Google 搜索,但无法找到是否可行。这就是问题所在。我有一个方法,它有一个字符串参数,我想匹配一个变量名。然后我想将该变量用于另一种方法。

所以简而言之,我会有一个参数字符串(例如“名称”) 并希望将其与变量“名称”匹配并获取/使用该值

类似的东西。

我的黄瓜场景会有这样一个步骤:

Abstract Scenario: check errors in fields
If there is an error in "field"
Then foo

Examples:
|field  |
|name   |
|address|
|phone  |

我在步骤定义中的方法类似于:

private final name = "field_ID_Name"
private final address = "field_ID_Address"
private final phone = "field_ID_Phone"

public void thereIsAnErrorIn(String field){
// Here the match from the argument "name" to use of the variable "name"
checkError(field)
}

private void checkError(String field){
// here I'd like to check based on the value, so in my case for variable
//'name' would get "field_ID_name" as passed parameter
seleniumdriver.pollVisible(field) //field = "field_ID_Name"
}

现在(显然)它将“name”作为字符串传递,但对于这个示例,我想不出一种传递“field_ID_Name”的方法。 我可以使用 switch 语句来检查字段的各种可能值,但我宁愿让它根据传递的字符串进行匹配。将精确定位器作为第一种方法的参数的另一种选择,但对于必须了解功能文件(黄瓜场景)的客户来说,这并不容易阅读。

任何建议表示赞赏!

【问题讨论】:

    标签: java regex selenium-webdriver cucumber


    【解决方案1】:

    您可以创建一个映射,其中变量名称作为键,所需的参数作为值传递给 pollVisible 函数。 所以你的地图看起来像:

    myMap : 名称 -> field_ID_Name

    现在做:

    private void checkError(String field){

    seleniumdriver.pollVisible(myMap.get(field));

    }

    【讨论】:

      【解决方案2】:

      您可以使用 Java 反射 API 读取对象字段值,这是最简单的方法 - 只需使用 Apache BeanUtils 库。看看这个类似的回答问题:

      Retrieve field values using BeanUtils

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-02
        相关资源
        最近更新 更多