0
votes

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());
    }
}
2
You just need to remove the redeclaration from the @Beforemethod for Webdriver. Rest all is fine - no change required. - niharika_neo
@niharika_neo, got it..working! Thanks!! - user3613402

2 Answers

0
votes

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

0
votes

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