微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WebElement Click在Selenium中显示NullPointerException

如何解决WebElement Click在Selenium中显示NullPointerException

我正在尝试https://www.yatra.com/etw-desktop/中的Selenium自动化测试。我的目标是单击一个名为“亚洲”的图像按钮,该按钮将重定向到另一页(附加图像)。我复制了完整的XPath并尝试了,但是却收到了NullPointerException。由于我的代码没有发现任何问题,请提供一些建议。

package com.stackroute.SeleniumProject;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;

/**
 * JUnit project.
 */
public class Yatra {
    public static WebDriver driver = null;
    @FindBy(xpath = "/html/body/my-app//app-drawer-layout/app-header-layout/iron-pages/my-home//div/div/div/div/paper-material[2]/div[1]/div/a[2]/div[4]")
    WebElement Asia;

    @BeforeClass
    public static void setup() {
        String chromePath = System.getProperty("user.dir") + "/lib/chromedriver.exe";// directory of chrome driver
        System.setProperty("webdriver.chrome.driver",chromePath);
        driver = new ChromeDriver();
    }

    @AfterClass
    public static void close() throws InterruptedException {
        driver.close();
    }

    @Test
    public void test1() throws InterruptedException {
        driver.manage().window().maximize();
        driver.get("https://www.yatra.com/etw-desktop/");
        driver.manage().timeouts().implicitlyWait(4000,TimeUnit.MILLISECONDS);
        Thread.sleep(5000);

        // the error is in the below line Asia.click()

        Asia.click();
        driver.manage().timeouts().implicitlyWait(5000,TimeUnit.MILLISECONDS);
        Thread.sleep(2000);

        Assert.assertEquals("page not found","https://www.yatra.com/etw-desktop/city-list",driver.getcurrenturl());
    }

}

Image showing the element to be clicked

Image of web page after click operation

解决方法

您正在使用PageFactory(来自页面对象模型),因此您需要init()网络元素。

为此,您需要导入

org.openqa.selenium.support.PageFactory;

在开始测试之前,您需要初始化元素:

PageFactory.initElements(driver,this)  // where you pass the driver and this class to know which webelements to start.

您可以在这里了解一下这种方法和另一个更易于理解的POM框架TUTORIAL

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。