Home > Blockchain >  How quit a window after selenium test? Problem with null in driver
How quit a window after selenium test? Problem with null in driver

Time:10-08

Selenium 4.5.0 I have a problem with quit a browser, when I start my test everything is good but in last element (tearDown) I have information about driver is null. How I can repair my code, that tearDown method will be good work and quit my browser, driver?

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import test.config.TestSettings;
import test.pages.BasePage;
import test.pages.LoginPage;
import java.time.Duration;

public class LoginPageTest {
    WebDriver driver;
LoginPage loginPage;
BasePage basePage;

@BeforeEach
public void setup(){
    System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver");
    WebDriver driver = new ChromeDriver();
    loginPage = PageFactory.initElements(driver, LoginPage.class);
    basePage = PageFactory.initElements(driver, BasePage.class);
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
    driver.manage().window().maximize();
    driver.get("mysite");
}

@Test
public void emptyPassword(){
    loginPage.setUsername("myaccountn");
    loginPage.clickSave();
    basePage.checkSite();
}

@AfterEach
public void tearDown(){
    driver.quit();
}

}

CodePudding user response:

Possibly the following is happening: WebDriver driver --> is already defined at the class level. But you are reassigning driver to another WebDriver under the setup method. Since it is a method level "WebDriver driver" its life is within the scope of method and not class.

If you remove the WebDriver at the method level it should work fine.

So it should look like the following:

public class LoginPageTest {

WebDriver driver;
LoginPage loginPage;
BasePage basePage;

@BeforeEach
public void setup(){
    System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver");
// --> remove the WebDriver here
    driver = new ChromeDriver();
    loginPage = PageFactory.initElements(driver, LoginPage.class);
    basePage = PageFactory.initElements(driver, BasePage.class);
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
    driver.manage().window().maximize();
    driver.get("mysite");
}

@Test
public void emptyPassword(){
    loginPage.setUsername("myaccountn");
    loginPage.clickSave();
    basePage.checkSite();
}

@AfterEach
public void tearDown(){
    driver.quit();
}

  • Related