Aakash Goyal Aakash Goyal - 2 months ago 23
Java Question

Unable to run TestNG test case in Eclipse with Chromedriver

I am new to Selenium and have written below code to open a site in chrome browser and verify its title. But when using 'System.setProperty()' to set the ChromeDriver Path, it gives me syntax error and when I commented the line I get - "java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property..."

My Code :

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class FirsttestNGFile {
String BaseURL = "http://newtours.demoaut.com/";
System.setProperty("webdriver.chrome.driver", "E:\\Automation Jars\\chromedriver_win32\\chromedriver.exe"); -- If I comment this line, I get Illegal state Exception for chromedriver path; if not commented , I get syntax error
WebDriver driver = new ChromeDriver();

@Test
public void verifyHomePageTitle() {
driver.get(BaseURL);
String ExpectedTitle = "Welcome: Mercury Tours";
String ActualTitle = driver.getTitle();
Assert.assertEquals(ExpectedTitle, ActualTitle);
driver.quit();
}
}


Please help.

Answer

You cannot define System.setProperty Globally. Use below code and try:

@Before
public void browser(){
 System.setProperty("webdriver.chrome.driver", "E:\\Automation Jars\\chromedriver_win32\\chromedriver.exe"); 
}

@Test
public void verifyHomePageTitle() {     

    String BaseURL = "http://newtours.demoaut.com/";

    WebDriver driver = new ChromeDriver();  
    driver.get(BaseURL);
    String ExpectedTitle = "Welcome: Mercury Tours";
    String ActualTitle = driver.getTitle();
    Assert.assertEquals(ExpectedTitle, ActualTitle);
    driver.quit();
}
}

If you are using Junit then use @Before or If you are using TestNG then @BeforeTest.

Reply me for further query. Happy Learning. :-)