Question

I have a HomePage. I am trying to test the title of the page in TestNG using test annotation. I am getting NullPointerException for testTitle().The url is opening.

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());
    }
}
Was it helpful?

Solution

Make WebDriver instance public and there is no need to create it's reference again in openBrowser() method. Use following code:

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());
    }
}

OTHER TIPS

Make driver a field in class, that way it will be initiate in openBrowser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top