我需要通过条件作为参数

时间:2019-06-27 10:26:55

标签: java selenium

基本上,我需要将一个条件作为参数传递给方法,并继续验证该条件,直到它更改其值为止。

下面有一个方法示例,该方法可以按某个键盘键直到满足条件为止。

例如,在某些情况下,我试图阅读服务条款页面,并且需要按“向下”,直到滚动条到达底部。

public static void pressKeyUntilCondition(Keys key, boolean condition) {
    while(condition) {
        press(key);
        timesPressed++;
    }
}

编辑: 另外,解决我的问题的另一种方法是,是否可以将方法传递到pressKeyUntilCondition()中,以便直接将Boolean getHeightFromBottom()方法发送到While条件中。

4 个答案:

答案 0 :(得分:3)

您可以为此使用谓词。谓词是布尔值函数。 这样,您就可以根据自己的价值进行测试,直到满足条件为止。

 public static void pressKeyUntilCondition(List<String> key, Predicate<YourObjectType> condition) {
    while(condition.test(yourValueToCheck)) {
        press(key);
        timesPressed++;
    }
}

答案 1 :(得分:1)

您可以将谓词传递给您的方法:

public static void pressKeyUntilCondition(Keys key, Predicate<Integer> condition) {
   while(condition.test(timesPressed)) {
      press(key);
      timesPressed++;
    }
}

例如,您通过的条件可能是:

Predicate<Integer> predicate = integer -> integer == 3;

如果需要更多“条件”进行评估,则可以创建一个包含这两个字段的模型类,并从中创建一个谓词:

public class ConditionValues {
        private int timesPressed;
        private Keys key;
        //getters setters
}

Predicate<ConditionValues> predicate = values -> values.getMaxTimePressed() ==  3 && values.getKey() == Keys.DOWN;

public static void pressKeyUntilCondition(Keys key, Predicate<ConditionValues> condition) {
    ConditionValues conditionValues = new ConditionValues(Keys.DOWN, 0);
    while(condition.test(conditionValues)) {
        press(key);
        timesPressed++;
        conditionValues.setTimesPressed(timesPressed);
    }

当然,这只是一个POC,因此您可以根据需要进行任何调整,例如,将所需的键作为参数传递。

答案 2 :(得分:0)

我没有得到确切的询问,但是据我了解,您可以执行以下操作。

如果要检查动态解决方案,则可以只检查方法而不是静态boolean条件。像这样:

private static final int BOTTOM_SCROLLBAR_POSITION = 777; // todo: change to your required position

private int getScrollBarPosition() {
    return 666; // todo: implement your scrollbar position logic
}

public void pressKeyUntilCondition(Keys key) {
    while (getScrollBarPosition() <= BOTTOM_SCROLLBAR_POSITION) { // using just an existing function
        press(key);
        timesPressed++;
    }
}

如果要传递可配置的条件,则可以使用java.util.function中的某些类,例如某些PredicateBooleanSupplier,例如:

private void callPressKeyUntilCondition() {
    pressKeyUntilCondition(
        Keys.ARROW_DOWN, 
        () -> getScrollBarPosition() <= BOTTOM_SCROLLBAR_POSITION // BooleanSupplier lambda implementation
    );
}

public void pressKeyUntilCondition(Keys key, BooleanSupplier conditionSupplier) {
    while ( !conditionSupplier.getAsBoolean() ) { // using just an existing function
        press(key);
        timesPressed++;
    }
}

答案 3 :(得分:-1)

您可能希望条件是可变的(不是最终的)。 因此,请考虑一些包含可以调用的实际值(或检查您需要执行的操作)的接口。

类似这样的东西:

public static void pressKeyUntilCondition(Keys key, Reference<Boolean> reference) {
    while(reference.get()) {
        press(key);
        timesPressed++;
    }
}

需要注意的另一点是,您在循环时不会消耗无限的cpu,因此您可能只希望偶尔检查该值,或者可能希望让线程进入睡眠状态,并且仅在条件满足时才唤醒它。

(因此,仅在不需要持续应用按键操作时才有效)