Selenium webdriver 在SeleniumWebDriver中的典型事件之前调用相同的方法

Selenium webdriver 在SeleniumWebDriver中的典型事件之前调用相同的方法,selenium-webdriver,Selenium Webdriver,在SeleniumWebDriver中,我必须在每个方法的每个“click/submit”事件之前调用一个特定的方法,无论这些事件出现在类中的哪个位置。我可以通过在每次单击/提交事件之前调用相同的方法(重复)来实现这一点。但是考虑一下在一个类中是否有总共100个点击事件。那会很麻烦。相反,我必须给出一些逻辑和条件,以便在一个地方调用一个方法,并为click/submit事件提供条件,然后在所有此类事件之前应用该方法 我怎样才能做到这一点 注意:Click/Submit事件的语句可能不同。创建一个

在SeleniumWebDriver中,我必须在每个方法的每个“click/submit”事件之前调用一个特定的方法,无论这些事件出现在类中的哪个位置。我可以通过在每次单击/提交事件之前调用相同的方法(重复)来实现这一点。但是考虑一下在一个类中是否有总共100个点击事件。那会很麻烦。相反,我必须给出一些逻辑和条件,以便在一个地方调用一个方法,并为click/submit事件提供条件,然后在所有此类事件之前应用该方法

我怎样才能做到这一点


注意:Click/Submit事件的语句可能不同。

创建一个参数自定义的Click/Submit方法(该方法可能接受要在其上执行操作的定位器),该方法在Click/Submit之前要调用,并在测试代码中使用该自定义方法


这将是一次性任务。

您可以使用包装类(并从中派生测试类)或使用静态方法。在Java中,它将如下所示:

   void extendedClick(WebElement webElement) {
        System.out.printf("Clicking on %1$s", webElement.toString());
        webElement.click();
    }
系统输出是您可以放置附加方法的地方。测试类可以调用

//normal click 
WebElement webElement = driver.findElement(By.xpath(element));
webElement.click();

如果不想使用包装类,可以将
extendedClick
放在静态上下文中,并相应地调用它。为了满足您要求的第二部分

我必须给出一些逻辑和条件,以便在 为单击/提交事件提供条件的一个位置,以及 随后,在所有此类事件之前应用

下面是一个静态上下文示例,其中条件(可在运行时确定)由调用方提供:

public class TestcaseHelper {
    private static boolean useExtension = false;

    /*** @param webElement element on which to perform click
     *   @param condition if true, extended click will be performed for this and any subsequent invocations
     */
    public static void extendedClick(WebElement webElement, boolean condition) {
        if (useExtension || condition) {
            useExtension = true;
            System.out.printf("Clicking on %1$s", webElement.toString());
        }
        webElement.click();
    }

    /** Reset extended click */
    public static void resetCondition() {
        useExtension = false;
    }
}
测试用例:

WebElement webElement = driver.findElement(By.xpath(element));
TestcaseHelper.extendedClick(webElement, this.determineIfConditionIsTrue());
或者在C#中,您也可以选择使用ExtensionMethod:

public static class ExtensionMethods
{
    public static void ExtendedClick(this IWebElement element)
    {
        DoFancyStuff();

        element.Click();
    }
}
注意
this
关键字,它实际上使您的静态方法成为IWebElement的扩展方法。然后,不是打电话

DoFancyStuff();
driver.FindElement(...).Click();
一次又一次,你只需打电话

driver.FindElement(...).ExtendedClick();

嗨,阿伦,你能用简单的示例代码详细说明一下吗。这将是一个很大的帮助!
driver.FindElement(...).ExtendedClick();