0

I am learning about POM Selenium + Java. I want to refactor class for tests. Right now I have one class but I want divide code into two class: one class will be for initializing browser with adnotations @BeforeClass and @AferClass and second will be with just @Test. When I refactor my code I get error java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.get(String)" because "this.driver" is null . My code only works if I have @After, @Before and @Test in one class.

My code for refactor:

public class TC1LoginRegisterUser {
    WebDriver driver;

    @Before
    public void setup() {
        driver = new ChromeDriver();
    }

    @Test
    public void test1() {
        HomePage homePage = new HomePage(driver);
        homePage.navigateToUrl();
    }

    @After
    public void teardown() {
        driver.close();
        driver.quit();
    }
}

My code after refactor:

public class BaseClass {

    WebDriver driver;
    @BeforeClass
    public void setup() {
        driver = new ChromeDriver();

    }

    @AfterClass
    public void teardown() {
        driver.close();
        driver.quit();
    }

}

public class TC1LoginRegisterUser extends BaseClass {
    @Test
    public void test1() {
        HomePage homePage = new HomePage(driver);
        homePage.navigateToUrl(); 
     }
}
2
  • Sure, this should work just fine, as long as your test class does indeed extend your base class. JUnit will run all the annotated methods. If it doesn't work for you, attach a debugger and see what gets executed when. Note that JUnit's default is to make a new instance of the test class for each test, so your driver field (and the before/after methods) should probably be static. Commented Jul 28, 2023 at 11:16
  • And note that BeforeClass and Before are different. Same for After. Read the javadoc on those classes for details. Commented Jul 28, 2023 at 11:18

1 Answer 1

0

To make your refactor work as expected, you should make method and driver variable static as far as @BeforeClass executes method when class instance has not been created yet, so non static entities are null.

static WebDriver driver;

@BeforeClass
public static void setupAll() {
   driver = new ChromeDriver();
}

but I suggest to use @Before except @BeforeClass annotation in your Base class, that would allow you to make driver non-static.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.