首页 > 解决方案 > 如何使用 Selenium 和 C# 修复测试自动化代码?

问题描述

我第一次使用 Selenium 和 C# 进行自动化测试。作为初学者,我正在按照此链接的一些说明进行操作。但是,它不起作用。它说 1 测试失败。我有以下代码:

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;


namespace OnlineStore.TestCases
{
    class LogInTest
    {
        [Test]
        public void Test()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Url = "http://www.store.demoqa.com";

            // Find the element that's ID attribute is 'account'(My Account) 
            driver.FindElement(By.XPath(".//*[@id='account']/a")).Click();

            // Find the element that's ID attribute is 'log' (Username)
            // Enter Username on the element found by above desc.
            driver.FindElement(By.Id("log")).SendKeys("testuser_1");

            // Find the element that's ID attribute is 'pwd' (Password)
            // Enter Password on the element found by the above desc.
            driver.FindElement(By.Id("pwd")).SendKeys("Test@123");

            // Now submit the form.
            driver.FindElement(By.Id("login")).Click();

            // Find the element that's ID attribute is 'account_logout' (Log Out)
            driver.FindElement(By.XPath(".//*[@id='account_logout']/a")).Click();

            // Close the driver
            driver.Quit();

        }
    }
}

以及以下消息:

[10/6/2019 5:05:53 AM Informational] Executing test method 'OnlineStore.TestCases.LogInTest.Test'
[10/6/2019 5:05:53 AM Informational] ------ Run test started ------
[10/6/2019 5:05:54 AM Informational] NUnit Adapter 3.15.1.0: Test execution started
[10/6/2019 5:05:54 AM Informational] Running selected tests in C:\Users\enead\source\repos\OnlineStore\OnlineStore\bin\Debug\OnlineStore.dll
[10/6/2019 5:05:55 AM Informational]    NUnit3TestExecutor converted 1 of 1 NUnit test cases
[10/6/2019 5:05:55 AM Informational] NUnit Adapter 3.15.1.0: Test execution complete
[10/6/2019 5:05:55 AM Informational] ========== Run test finished: 1 run (0:00:01.8817664) ==========

我搜索了多个网站以找到答案,但没有成功。怎么了?我能做些什么?
编辑
我提供了一些屏幕截图。

1 测试失败

错误信息

指定驱动程序位置后出错

标签: c#seleniumselenium-webdriverautomated-testsselenium-chromedriver

解决方案


  1. 此页面顶部有一个横幅阻止了“帐户”元素。 在此处输入图像描述 您需要添加一个测试步骤,您首先单击以“关闭”此横幅。

driver.FindElement(By.LinkText("Dismiss").Click();

  1. Visual Studio 中的脚本将始终比浏览器移动得更快,因此您需要在脚本中添加步骤,等待页面加载,然后再单击新元素。

一个简单的方法是使用这样的静态等待方法:

Task.Delay(2000).Wait();

您还需要添加: using System.Threading.Tasks;

'2000' 是您要等待的毫秒数。

一种更动态的等待方式是首先创建一个等待方法,然后在您想要wait发生特定的事情时调用该方法(在这种情况下,等待帐户链接可点击)。

创建一个动态等待方法并使用它看起来像这样:

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("By.LinkText("My Account"))).Click();

对于这种方法,您还需要:using OpenQA.Selenium.Support.UI;


推荐阅读