无法使用ChromeDriver在Eclipse中运行TestNG测试用例

时间:2016-09-16 10:35:47

标签: java eclipse selenium testng

我在下面编写了代码,用于在Chrome浏览器中打开网站并验证其标题。但是当使用System.setProperty()设置ChromeDriver路径时,它会给我语法错误,当我评论我得到的行时:

java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property..

我的代码:

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

3 个答案:

答案 0 :(得分:1)

您无法在全球范围内定义System.setProperty。 使用下面的代码并尝试:

WebDriver driver;
@Before
public void browser(){
 System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\CP-SAT\\Chromedriver\\chromedriver.exe"); 
 driver = new ChromeDriver(); 
}

@Test
public void verifyHomePageTitle() {     

    String BaseURL = "http://newtours.demoaut.com/";
    driver.get(BaseURL);
    String ExpectedTitle = "Welcome: Mercury Tours";
    String ActualTitle = driver.getTitle();
    Assert.assertEquals(ExpectedTitle, ActualTitle);
    }

@Test
public void a() {
    driver.get("https://www.google.co.in/?gfe_rd=cr&ei=6PDbV-qTAZHT8gecr4qQBA");    
} 

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

如果您使用Junit,请使用@Before或如果您使用的是TestNG,请@BeforeTest

回复我以进一步查询。 快乐学习。 : - )

答案 1 :(得分:1)

您应该考虑使用https://github.com/bonigarcia/webdrivermanager来为您完成工作:

ChromeDriverManager.getInstance().setup();

答案 2 :(得分:0)

更新环境变量路径中的chrome驱动程序路径,然后尝试在脚本中使用以下代码

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