【问题标题】:NullPointerException on image verification in Selenium在 Selenium 中进行图像验证时出现 NullPointerException
【发布时间】:2016-12-09 01:05:12
【问题描述】:

我正在使用 Selenium Server 和 Java 并尝试验证图像是否实际显示。 我正在使用以下代码,但得到NullPointerException

String imageURL = driver.findElement(By.xpath(imageXpath)).getAttribute("src");
assertTrue((Boolean) ((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", imageURL));

当我手动验证存储在变量 imageURL 中的 URL 时,我得到了一个有效的图像,因此我不明白为什么会得到一个 NullPointerException

【问题讨论】:

  • 请提供异常日志

标签: javascript java selenium selenium-webdriver


【解决方案1】:

可能是executeScript() 正在返回null,这就是你得到NullPointerException 的原因,这可能是由于时间问题,你提供的javascript 将返回null 而不是预期值,在这种情况下你应该尝试使用executeAsyncScript(),它将实现callback函数并等待预期值返回如下:-

//this is the time out for executing async javascript
driver.manage().timeouts().setScriptTimeout(10,TimeUnit.SECONDS);

WebElement imageURL = driver.findElement(By.xpath(imageXpath));   
assertTrue((Boolean) ((JavascriptExecutor)driver).executeAsyncScript("callback = arguments[1];callback(arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0)", imageURL));

希望对您有所帮助...:)

【讨论】:

  • @Taly 你能分享一下确切的堆栈跟踪吗??
  • @Taly 省略 .getAttribute("src") 并尝试...查看更新的答案..:)
  • 我按照您的建议省略了 .getAttribute("src") 并将其另存为 WebElement(而不是 String)并解决了它 - 非常感谢!!
【解决方案2】:

空指针异常是因为executeScript 返回null,而您的代码期待Boolean

它返回 null,因为您的脚本正在访问 String 上的一些 HTMLElement 属性(完整、自然宽度),这是提供给 executeScript 的第二个参数。

为了让它发挥作用:

WebElement image = driver.findElement(By.xpath(imageXpath));

assertTrue((Boolean)((JavascriptExecutor)driver).executeScript(
  "return !!arguments[0].complete && arguments[0].naturalWidth > 0;"
  , image))

【讨论】:

  • 非常感谢!!这真的很有帮助,确实解决了问题!
【解决方案3】:

你能不能改一下

String imageURL = driver.findElement(By.xpath(imageXpath)).getAttribute("src");

String imageURL = driver.findElement(By.xpath(imageXpath));

我希望其余代码正确或使用简单检查 -

Boolean imageLoaded1 = (Boolean)((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", imageURL);
  if (!imageLoaded1){
     System.out.println("Image is not present");
  }else{
     System.out.println("Got it");
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2014-06-21
    • 2012-06-26
    相关资源
    最近更新 更多