空指针异常TestNG

时间:2014-05-08 20:28:28

标签: selenium-webdriver testng

我有一个主页。我试图使用测试注释在TestNG中测试页面的标题。我正在为testTitle()获取NullPointerException。这个url正在打开。

public class HomePage {

    WebDriver driver;

    public HomePage(WebDriver driver){
        this.driver= driver;
    }
}

public class HomePageTest {
    WebDriver driver;

    @BeforeMethod
    public void openBrowser(){
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.get("URL to open");
    }

    @Test
    public void testTitle(){
        HomePage page = new HomePage(driver);
        Assert.assertEquals("actualTitle", driver.getTitle());
    }
}

2 个答案:

答案 0 :(得分:0)

在类中使驱动程序成为一个字段,这样它将在openBrowser中启动。

答案 1 :(得分:0)

公开WebDriver个实例,无需再次在openBrowser()方法中创建它的引用。使用以下代码:

public class HomePageTest {
    public WebDriver driver; //driver instance is public

    @BeforeMethod
    public void openBrowser(){
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.get("URL to open");
    }

    @Test
    public void testTitle(){
        HomePage page = new HomePage(driver);
        Assert.assertEquals("actualTitle", driver.getTitle());
    }
}