2

我一直在使用 Firefox 来运行我的测试用例。但现在我想使用 Chrome。我想在类级别初始化 chrome,就像我使用 Firefox 一样。但是在类级别设置系统属性会出错,我该怎么办?使用属性文件会起作用,如果是的话,如何?

public class BaseClass {
System.setProperty("webdriver.chrome.driver","/home/Desktop/chrome32/chromedriver"); 
public static WebDriver driver = new ChromeDriver();

public void test(){
driver.get("http://asdf.com");

----
---
 }

}
4

4 回答 4

4

您可以使用这样的静态初始化程序块来冷处理:

public class BaseClass {

  static {
    System.setProperty("webdriver.chrome.driver","/home/Desktop/chrome32/chromedriver");
  }

  protected WebDriver driver = new ChromeDriver();

  @Test
  public void test(){
    driver.get("http://asdf.com");
  }
}

由于您没有说明您正在使用哪个测试框架,您可能会在 TestNG 中这样做(无论如何我都会推荐):

public class BaseClass {

  @BeforeSuite
  public void setupChromeDriver() {
    System.setProperty("webdriver.chrome.driver","/home/Desktop/chrome32/chromedriver");
  }

  public static WebDriver driver = new ChromeDriver();

  public void test(){
    driver.get("http://asdf.com");
  }
}

@BeforeSuite 注释确保该方法在测试套件的第一个测试运行之前执行,所以无论如何这应该足够早。

于 2013-04-03T04:34:50.007 回答
2

请以这种方式声明它..它应该工作

public class abcd {


public static WebDriver driver;


@BeforeMethod
public static void start() 
{
    File file = new File("D:/abcd/chromedriver.exe");
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    driver = new ChromeDriver();
            }
}

它应该工作..我有同样的错误。但是当你以这种方式初始化时它可以工作。请尝试让我们知道。

如果您不想关闭浏览器会话,请尝试使用@BeforeClass 和@AfterClass。它在整个测试之前运行一次

于 2013-05-08T09:29:44.030 回答
1

为什么不尝试在基类的 @BeforeTest 方法中初始化 Chrome 驱动程序。我所做的是这样的:

public class BaseTest { 

    /*
     * 
     * This is a base class for all Test classes that we'll create to write tests in.
     * A test-data set will belong to one/set of tests.
     */


    protected WebDriver driver;
    protected CustomLogger logger;
    protected DependencyChecker dcheck;
    protected TestDataReader td;
    protected PropReader p;
    protected HashMap<String, String> testDataMap;
    private String testDataFilePath;


    protected BaseTest(String testDataFilePath) 
    {
        this.testDataFilePath = testDataFilePath;
        p = new PropReader("environmentConfig.properties");
    }


    @BeforeTest(description="Preparing environment for the test..")
    public void prepareTest()
    {

        //other code
        System.setProperty(p.get("chromeDriverName"),p.get("chromeDriverPath"));
        File chrome = new File("/usr/bin/google-chrome");
        ChromeOptions options = new ChromeOptions();
        options.setBinary(chrome);
        logger.log("Launching browser..");
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        //other code        
    } 
    }


我不知道您为什么要在班级级别对其进行初始化。上面的代码工作得很好。

于 2013-04-02T07:37:36.363 回答
1
System.setProperty("webdriver.chrome.driver","/home/Desktop/chrome32/chromedriver");

这一行应该在一个方法中,你不能直接在你的类体内使用它

于 2013-04-02T07:01:43.487 回答