Selenium Grid本地实现自动化UI测试

image.png

Selenium Grid工作原理

Selenium Grid实际它是基于Selenium RC的,而所谓的分布式结构就是由一个hub节点和若干个node代理节点组成。Hub用来管理各个代理节点的注册信息和状态信息,并且接受远程客户端代码的请求调用,然后把请求的命令转发给代理节点来执行。下面结合环境部署来理解Hub与node节点的关系。

本地启动Selenium Grid

docker-compose.yml

  1. version: "3"
  2. services:
  3. selenium-hub:
  4. image: selenium/hub:3.141.59-bismuth
  5. container_name: selenium-hub
  6. ports:
  7. - "4444:4444"
  8. chrome:
  9. image: selenium/node-chrome:3.141.59-bismuth
  10. depends_on:
  11. - selenium-hub
  12. environment:
  13. - HUB_HOST=selenium-hub
  14. - HUB_PORT=4444
  15. firefox:
  16. image: selenium/node-firefox:3.141.59-bismuth
  17. depends_on:
  18. - selenium-hub
  19. environment:
  20. - HUB_HOST=selenium-hub
  21. - HUB_PORT=4444

启动两个chrome、两个firefox 节点

  1. docker-compose up -d --scale chrome=2 --scale firefox=2

image.png

image.png

运行本地测试用例

示例代码

  1. public abstract class BaseTest
  2. {
  3. private IWebDriver _driver;
  4. public string Url => "http://52.187.72.74:5001/#/FoodCategory";
  5. public IWebDriver GetDriver(DriverOptions options)
  6. {
  7. //InternetExplorerOptions Options = new InternetExplorerOptions();
  8. if (_driver == null)
  9. {
  10. _driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub/"), options.ToCapabilities(), TimeSpan.FromSeconds(600));
  11. }
  12. return _driver;
  13. }
  14. }
  1. [Fact]
  2. public void AddFoodCategory()
  3. {
  4. using (var driver = GetDriver(new ChromeOptions()))
  5. {
  6. driver.Navigate().GoToUrl(Url);
  7. driver.FindElement(By.CssSelector(".btn-primary")).Click();
  8. driver.FindElement(By.Id("food-category-name")).Click();
  9. driver.FindElement(By.Id("food-category-name")).Click();
  10. driver.FindElement(By.Id("food-category-name")).SendKeys("蔬菜");
  11. driver.FindElement(By.Id("food-category-description")).Click();
  12. driver.FindElement(By.Id("food-category-description")).SendKeys("蔬菜");
  13. //var text = driver.FindElement(By.Id("food-category-description")).GetProperty("value");
  14. driver.FindElement(By.CssSelector("#add-modal .btn-outline-primary")).Click();
  15. var latsTitle = driver.FindElement(By.CssSelector(".el-table__fixed-body-wrapper .el-table__row:last-child .el-table_1_column_3 .cell")).GetProperty("innerHTML");
  16. Assert.Equal("蔬菜", latsTitle);
  17. }
  18. }

测试结果

image.png