Java,Selenium和Method.invoke:获取NoSuchMethodException

问题描述

目标:创建我自己的方法,该方法调用传递给它的Selenium方法并将该方法重复指定的次数。

问题:无论我尝试什么,总是会产生以下代码: java.lang.NoSuchMethodException:org.openqa.selenium.WebDriver.sendKeys()

讨论:据我所知,sendKeys()作为org.openqa.selenium.WebDriver中的一种方法存在

问题代码:

Method objTest = WebDriver.class.getMethod(strMethod,CharSequence.class);

strMethod = sendKeys

代码

R

我在main()中调用我的repeatAction()方法:

public void repeatAction(String strMethod,int numberOfTimes) throws NoSuchMethodException,SecurityException,IllegalAccessException,IllegalArgumentException,InvocationTargetException {
    int i = 0;
    Method objTest = WebDriver.class.getMethod(strMethod,CharSequence.class); // PROBLEM CODE - results in NoSuchMethodException
    while (i <= numberOfTimes) {
        objTest.invoke(strMethod,Keys.DOWN);  // I've hardcoded Keys.DOWN for now but will make this flexible later
        i++;
    }
}

运行时错误

AutocompleteDropdownPractice objADDP = new AutocompleteDropdownPractice();
objADDP.repeatAction("sendKeys",5);     // Repeat Selenium WebDriver's sendKeys() 5 times

对于我做错了什么以及应该如何做的任何帮助,将不胜感激。

解决方法

如果您查看Selenium API,您会发现WebDriver类没有任何方法作为sendKeys(),这就是为什么您会收到NoSuchMethodException的原因。

我认为您正在寻找org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence... keysToSend)方法,在您的情况下,您可以按以下方式使用它:

Method objTest = WebElement.class.getMethod(strMethod,CharSequence[].class);

我使用的是数组版本CharSequence[].class而不是CharSequence.class,因为sendKeys方法接受CharSequence.class的数组,可以在API docs中清楚地看到。

,

第一

如果您参考Java文档,则会看到invoke() method带有两个参数:

  1. 您从中调用方法的对象(因为您需要该对象来调用非静态方法)
  2. 方法参数

您的示例中的这些行:

Method objTest = WebDriver.class.getMethod(strMethod,CharSequence.class);
objTest.invoke(strMethod,Keys.DOWN);

意味着您从WebDriver类中获取方法,并在不正确的String对象上调用它。

第二

sendKeys方法是在WebElement接口中声明的,而不是在WebDriver中声明的。

第三

您可以尝试使用Proxy对象来完成此操作,如下所示:

public WebElement poxiedElement(String methodName,int times,WebElement element){
    return (WebElement) Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{WebElement.class},new InvocationHandler() {
        @Override
        public Object invoke(Object o,Method method,Object[] objects) throws Throwable {
            Object[] results = new Object[times];
            if(methodName.equals(method.getName())){
                for(int i = 0; i < times; i++){
                    results[i] = method.invoke(element,objects);
                }
            }
            return results;
        }
    });
}

void test(){
    WebElement element = driver.findElement(By.xpath("..."));
    poxiedElement("sendKeys",5,element).sendKeys("blah");
}

PS -您应该了解方法可以返回值。因此,多次调用任何方法都可能返回多个值。您必须考虑这一点。在我的示例中,该方法将返回array个结果。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...