Selenium可以用来做自动化UI测试,支持多语言,这里使用C#编写测试脚本

.NetFramework

Selenium.SupportSelenium.WebDriver,Selenium.RC

dotnet core

核心库:Selenium.SupportSelenium.WebDriver,Selenium.Chrome.WebDriver

Selenium.RC包在dotnetcore会存在不兼容的问题,无法正常找到chromedriver.exe文件

Exception

The chromedriver.exe file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at http://chromedriver.storage.googleapis.com/index.html.”

解决方法

nuget Selenium.Chrome.WebDriver。将ChromeDriver.exe放入构建目录中

注意:.netcore2.1中引入了Selenium.Chrome.WebDriver包依旧会出现上面的异常

浏览器驱动下载

需下载本机对应版本,不区分32/64

https://npm.taobao.org/mirrors/chromedriver/

PageObject

解决的问题:版本迭代太快,UI层元素的属性经常变换,导致维护人员需要花大把的时间去维护代码,为了节省维护成本及时间,就可以利用PageObject 这种设计模式,它就大大的减少了维护时间

实践

TestBase

创建对应浏览器配置,创建WebDriver对象

  1. public abstract class TestBase
  2. {
  3. protected IWebDriver driver;
  4. public void WebDriverInit(string url)
  5. {
  6. ChromeOptions options = new ChromeOptions();
  7. // 窗口最大化
  8. options.AddArgument("start-maximized");
  9. driver = new ChromeDriver(options);
  10. driver.Navigate().GoToUrl(url);
  11. Thread.Sleep(1000);
  12. }
  13. }

ClockInPage

页面模型,封装页面标签属性以及对应操作

  1. public class ClockInPage
  2. {
  3. public static class PagePath
  4. {
  5. public static readonly string input_loginName_id = "tb_LoginID_Account_589f1fc067ff4031";
  6. public static readonly string input_passWord_id = "tb_Password";
  7. public static readonly string submit_login_Name = "ctl10";
  8. }
  9. public void LoginClick(IWebDriver driver, string logiName, string passWord)
  10. {
  11. driver.FindElement(By
  12. .Id(PagePath.input_loginName_id)).SendKeys(logiName);
  13. driver.FindElement(By
  14. .Id(PagePath.input_passWord_id)).SendKeys(passWord);
  15. driver.FindElement(By
  16. .Name(PagePath.submit_login_Name)).Click();
  17. Thread.Sleep(1000);
  18. }
  19. }

ClockInTests

测试方法,采用DDT数据驱动方式提供测试数据

  1. [TestCategory("ui\\CodedUITest")]
  2. [TestClass()]
  3. public class ClockInTests : TestBase
  4. {
  5. [TestCleanup]
  6. public void Clean()
  7. {
  8. driver.Dispose();
  9. }
  10. [DataTestMethod]
  11. [DataRow("http://11.11.141.10/OMSP//Login/JSS.aspx", "wangpengliang", "Wpl-19950815", true)]
  12. [DataRow("http://11.11.141.10/OMSP//Login/JSS.aspx", "111111", "222222", false)]
  13. public void ClockIn_Login_01_Normal(string url, string loginName, string passWord, bool expect)
  14. {
  15. WebDriverInit(url);
  16. ClockInPage page = new ClockInPage();
  17. page.LoginClick(driver, loginName, passWord);
  18. Assert.AreEqual(expect, driver.Url != url);
  19. }
  20. }