为什么我的 [TestMethods] 不能引用我在 [test initialize] 中制作的浏览器?

Why can't my [TestMethods] reference the browser I made in [test initialize]?

在我的 selenium webdriver 单元测试中,我在顶部有一个 [TestInitialize] 部分,只是为了设置浏览器,它在所有测试中重复出现并且不是很漂亮。

我的问题是,在实际的 [TestMethod] 中,我在 Initialize 中设置的 Chrome 浏览器(即变量名 "d")未被识别。当我在测试方法中将鼠标悬停在 "d" 上时,它显示 "the name 'd' does not exist in the current context."

我发现我在这里犯了一个相当低级的错误,有人可以用简单的方式解释我做错了什么(希望是我应该做什么)吗?

[TestInitialize]
public void TestSetup()
{
    IWebDriver d = new ChromeDriver("C:\location\of\my\chrome_driver\is_here\");
    d.Manage().Cookies.DeleteAllCookies();
    d.Manage().Window.Maximize();
}

[TestMethod]
public void ClickTrumpet_LouieArmstrongMusicPlays()
{            
    d.Navigate().GoToUrl("http://bupitybop.kom/");

    for (int i = 0; i < 12; i++)
    {
        d.FindElement(By.ClassName("boopi-boopi")).Click();
    }
    d.Quit();
}

d声明在TestSetup()的范围内。它在 TestSetup() 之外不可用。为了解决这个问题,使它成为一个实例变量,以便它在整个测试中都有作用域 class.

IWebDriver d;

[TestInitialize]
public void TestSetup()
{
    d = new ChromeDriver("C:\location\of\my\chrome_driver\is_here\");
    d.Manage().Cookies.DeleteAllCookies();
    d.Manage().Window.Maximize();
}

[TestMethod]
public void ClickTrumpet_LouieArmstrongMusicPlays()
{            
    d.Navigate().GoToUrl("http://bupitybop.kom/");

    for (int i = 0; i < 12; i++)
    {
        d.FindElement(By.ClassName("boopi-boopi")).Click();
    }
    d.Quit();
}