【问题标题】:How do I pass reference to active driver between classes如何在类之间传递对活动驱动程序的引用
【发布时间】:2017-07-04 13:11:33
【问题描述】:

我的问题是,当驱动程序在 FetchName 方法中设置名字时,我收到一条错误消息,指出驱动程序为空。我可以通过某种方式传递活动驱动程序实例以便继续获取数据吗?

[TestFixture]
public class TestBase
{
    protected IWebDriver driverChrome;

    [SetUp]
    public void Setup()
    {
        driverChrome = new ChromeDriver();
    }


    [TearDown]
    public void CleanSite()
    {
        driverChrome.Quit();
    }

}

我在其中创建所有 [测试] 方法的“测试”类。

public void tests: Testbase
{
        [Test]
        public void testmethods()
        {
            string blabla = driverChrome.FindElement(By.id("dsd")).Text;
            Reuse.FetchName(out string firstname, out string lastname);
            Assert.isTrue(firstname.equals(lastname));
        } 
}

一个类“重用”,其中我有 [test] 方法将多次使用的方法。

public class Reuse: Testbase
{
    [Test]
    public void FetchName(out string firstname, out string lastname)
    {
            firstname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
            lastname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text; 
    }
}

【问题讨论】:

  • 你可以让你driverChrome作为一个全局变量或者写一个getter setter来获取驱动实例。

标签: c# google-chrome selenium-webdriver nunit


【解决方案1】:
  1. Reuse 类不是测试用例。当您向方法添加属性[Test] 时,该方法应该包含一个断言。所以Reuse 不应该继承自Testbase
  2. 如果你想拥有一个包含多个动作的类,它应该是静态类。
  3. WebDriver 是一个独立的进程。您可以使用多个类或多个进程来访问它。他们都将获得相同的 WebDriver。

下面的示例展示了如何更改Reuse 类以及如何使用它。

public static class Reuse
{
    public static IWebDriver driverChrome;
    public static void FetchName(out string firstname, out string lastname)
    {
            firstname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
            lastname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text; 
    }
}

你可以这样称呼它。

public void tests: Testbase
{
    [Test]
    public void testmethods()
    {
        string blabla = driverChrome.FindElement(By.id("dsd")).Text;
        Reuse.driverChrome = driverChrome;
        Reuse.FetchName(out string firstname, out string lastname);
        Assert.isTrue(firstname.equals(lastname));
    } 

}

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2015-03-05
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2014-12-08
    相关资源
    最近更新 更多