user2376425
user2376425

Reputation: 85

Execute test method in junit4

Environment : Eclipse, Selenium-webdriver 2.31, Junit4. I am modifying some scripts, n now when i execute this snippet the browser of chrome is started twice and thats obvious but am not sure how to start chrome only once and execute test method. Please correct me.

Thats my LoginPage class, where the parameters are passed. Here if i don't initialize WebDriver instance, then NPE Exception will be popped up.

Code :

@RunWith(Parameterized.class)
public class LoginPage{
WebDriver driver = new ChromeDriver();
String username;
String password;

public LoginPage(String username, String password)
{
    this.username = username;
    this.password = password;
    }

@Test
public void loginAs(){
    user.sendKeys(this.username);
    pass.sendKeys(this.password);


}

}

Now thats the Suite class, where suite classes are mentioned. Link class is some another class.

TestSuite Class Code :

@RunWith(Suite.class)
@SuiteClasses({
LoginPage.class, Link.class
})
public class LoginTest{
static WebDriver driver;
@BeforeClass
public static void start()throws Exception
{
    System.setProperty("webdriver.chrome.driver", "E:/Selenium/lib/chromedriver.exe");
    driver = new ChromeDriver();
    driver.get("URL");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    System.out.println("Before Class");
}
@AfterClass
public static void teardown()
{
  //
}

Upvotes: 0

Views: 169

Answers (1)

Erki M.
Erki M.

Reputation: 5072

You are creating 2 chrome instances in your code: First when your @BeforeClass

@BeforeClass
public static void start()throws Exception
{
    System.setProperty("webdriver.chrome.driver", "E:/Selenium/lib/chromedriver.exe");
    driver = new ChromeDriver();

And the again when you create LoginPage object.

public class LoginPage{

     WebDriver driver = new ChromeDriver();

So depending on your need, you have to remove one of these.

I cant really see where the user and pass variables are assigned, but assuming they are webelements you probably get them from driver. So if you don't initiate driver in LoginPage you get nullpointer indeed.

If you still need to start the driver in your @BeforeClass and you want to use the same driver instance in your code, you could get a getter for this.

@RunWith(Suite.class)
@SuiteClasses({
LoginPage.class, Link.class
})
public class LoginTest{
static WebDriver driver;

public WebDriver getWebDriver(){
    return driver; }
@BeforeClass
......

and you can call it in you constructor of login:

WebDriver driver;


public LoginPage(String username, String password)
{
    this.username = username;
    this.password = password;
    driver = LoginTest.getWebDriver();
    }

Upvotes: 3

Related Questions