C# Selenium WebDriver 测试在连续 运行 时失败,但在单独 运行 时成功

C# Selenium WebDriver tests failing when run consecutively but succeeding when run individually

所以我有一个 .feature 文件,我在其中添加了 4 个场景。

.特征文件

Feature: BleKeys beheren
Het beheren van BLE-keys
d.m.v. de WebInterface.

@notfs
Scenario: BLE-key toevoegen aan database
    Given I'm at the BleKey/Create page.
    And I have entered acceptable BLE-data.
    When I press Create
    Then The BLE-key should be added to the database.

@notfs
Scenario: BLE-key data aanpassen
    Given There is a BleKey in the database.
    And I'm at the BleKey/Edit page of that BleKey
    When I edit the MAC-Adress
    And I edit the Conditional Report
    And I edit the Flag
    And I edit the Distance
    And I edit the Reference
    And I edit the ExtraCfg
    And I press Save
    Then The BleKey should have changed correctly.

@notfs
Scenario: BLE-key data verwijderen
    Given There is a BleKey in the database.
    And I navigate to the Delete page of that BleKey
    When I press Delete
    Then The BleKey should be deleted.

@notfs
Scenario: BLE-key data van 1 sleutel bekijken
    Given There is a BleKey in the database.
    And I navigate to the Details page of that BleKey
    Then The correct data of that BleKey should be displayed

现在,当我 运行 Visual Studio(ReSharper 单元测试会话 Window)中的这些测试分别成功时,但是当 运行 连续第一个成功但任何连续测试均失败,但出现以下异常:

OpenQA.Selenium.WebDriverException : Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:5595

如您所见,测试尝试连接到某个本地 IP 地址,而它应该导航到 URL 的基础地址:

http://localhost:58759/ + controller + method depending on the test.

我在步骤文件中创建了 WebDriver 实例。像这样:

public class BleKeyBeherenSteps
    {
        public static RemoteWebDriver RemoteWebDriver = new ChromeDriver();
        public WebinterfaceSelenium SeleniumTest = new 
        WebinterfaceSelenium(RemoteWebDriver);
        public Navigate Navigate = new Navigate(RemoteWebDriver);
        public Check Check = new Check(RemoteWebDriver);
        public Edit Edit = new Edit(RemoteWebDriver);
        public Delete Delete = new Delete(RemoteWebDriver);
        private readonly BeheerContext _db = new BeheerContext();
    }

在我的方法中,我是这样导航的:

Driver.Navigate().GoToUrl(Adress + BleKeyIndexUrl);

其中地址 = "http://localhost:58759/"

和 BleKeyIndexUrl = "BleKeys/Index"

因此出于某种原因,WebDriver 导航到本地 IP 地址而不是本地主机地址。

编辑:每次测试后我关闭驱动程序:Driver.Quit(); 我的猜测是,由于某种原因,在第一次测试后 Driver.Url 属性 丢失了。

不要担心本地主机到 IP 地址的歧义,本地主机通常解析为 127.0.0.1。

连续单元测试失败通常是由于在应用程序代码中使用静态声明引起的。今天早上我处理了这个问题,我不得不在每个单元测试开始时在我的应用程序深处重置一个麻烦的静态变量。