在NUnit中运行并行测试时保持Selenium WebDriver的上下文?

时间:2018-03-27 23:03:47

标签: selenium selenium-webdriver nunit

使用:
C#
NUnit 3.9
Selenium WebDriver 3.11.0
Chrome WebDriver 2.35.0

在NUnit中运行并行测试时,如何维护WebDriver的上下文?

  • 当我使用ParallelScope.All属性运行测试时,我的测试重用了驱动程序并失败

  • 我的测试中的Test属性不会在[Setup] - [Test] - [TearDown]中持续存在,而不会给测试提供更高的范围。

test.cs中

public class Test{
    public IWebDriver Driver;
    //public Pages pages;
    //anything else I need in a test

    public Test(){
        Driver = new ChromeDriver();
    }

    //helper functions and reusable functions
}

SimpleTest.cs

[TestFixture]
[Parallelizable(ParallelScope.All)]
class MyTests{

    Test Test;

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

    [Test]
    public void Test_001(){
        Test.Driver.Goto("https://www.google.com/");
        IWebElement googleInput = Test.Driver.FindElement(By.Id("lst-ib"));
        googleInput.SendKeys("Nunit passing context");
        googleInput.SendKeys(Keys.Return);
    }
    [Test]
    public void Test_002(){
        Test.Driver.Goto("https://www.google.com/");
        IWebElement googleInput = Test.Driver.FindElement(By.Id("lst-ib"));
        googleInput.SendKeys("Nunit passing context");
        googleInput.SendKeys(Keys.Return);
    }
    [Test]
    public void Test_003(){
        Test.Driver.Goto("https://www.google.com/");
        IWebElement googleInput = Test.Driver.FindElement(By.Id("lst-ib"));
        googleInput.SendKeys("Nunit passing context");
        googleInput.SendKeys(Keys.Return);
    }
    [Test]
    public void Test_004(){
        Test.Driver.Goto("https://www.google.com/");
        IWebElement googleInput = Test.Driver.FindElement(By.Id("lst-ib"));
        googleInput.SendKeys("Nunit passing context");
        googleInput.SendKeys(Keys.Return);
    }

    [TearDown]
    public void TearDown()
    {

        string outcome = TestContext.CurrentContext.Result.Outcome.ToString();
        TestContext.Out.WriteLine("@RESULT: " + outcome);
        if (outcome.ToLower().Contains("fail"))
        {
            //Do something like take a screenshot which requires the WebDriver
        }
        Test.Driver.Quit();
        Test.Driver.Dispose();
    }
}


  • The docs state“SetUpAttribute现在专门用于每次测试设置。”

  • 在[Setup]中设置Test属性似乎不起作用。

  • 如果这是一个计时问题,因为我正在重新使用Test属性。如何安排我的灯具,使每个测试的驱动程序都是唯一的?

  • 一种解决方案是将驱动程序放在[Test]中。但是,我无法使用TearDown方法,这是保持我的测试有条理和清理的必要条件。

  • 我已经阅读了不少帖子/网站,但没有解决问题。 [Parallelizable(ParallelScope.Self)]似乎是唯一真正的解决方案,并且会减慢测试速度。

提前谢谢!

1 个答案:

答案 0 :(得分:2)

ParallelizableAttribute向NUnit承诺,并行运行某些测试是安全的,但实际上使其安全并没有做任何事情。这取决于你,程序员。

您的测试(测试方法)具有共享状态,即字段Test。不仅如此,每个测试都会更改共享状态,因为每个测试都会调用SetUp方法。这意味着您的测试可能无法安全地并行运行,因此您不应该告诉NUnit以这种方式运行它们。

您有两种方法可以使用较低程度的并行性或使测试安全并行运行。

使用较小程度的并行性是最简单的。尝试在装配体上使用ParallelScope.Fixtures或在每个夹具上使用ParallelScope.Self(默认值)。如果你有大量的独立装置,这可能会给你提供良好的吞吐量,因为你会做更复杂的事情。

或者,要并行运行测试,每个测试必须有一个单独的驱动程序。您必须创建它并在测试方法本身中处理它。

将来,NUnit可以通过在单独的对象中隔离每个测试方法来添加一个使这更容易的功能。但是使用当前的软件,上面是你能做的最好的。