如何使用chrome和Firefox使用C#mstest运行一些测试用例?

问题描述

共有10个测试用例。我需要使用chrome运行一些测试用例,例如,使用chrome运行1-3和6-8测试用例,使用firefox运行4-5和9-10测试用例。

帮助文件中的代码

static public IWebDriver GetWebDriverC(browserType brt)
        {
            ChromeOptions coption = new ChromeOptions();
            coption.AddArgument("no-sandBox");
            driver = new ChromeDriver(coption);
            driver.Navigate().GoToUrl(url);
            return driver;
            
        }

        static public IWebDriver GetWebDriverFF(browserType brt,string url,string username,string password)
        {
            FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
            service.FirefoxBinaryPath = @"path";
            driver = new FirefoxDriver(service);
            driver.Navigate().GoToUrl(url);
            bool ele1 = AutoItX.WinExists("[CLASS:MozillaDialogClass]") == 1;
            if (ele1)
            {
                AutoItX.WinActivate("[CLASS:MozillaDialogClass]");
                AutoItX.Send(username);
                AutoItX.Send("{TAB}");
                AutoItX.Send(password);
                AutoItX.Send("{ENTER}");
            }

            return driver;
        }

不同用户用户名密码不同。 主文件中有多个测试用例

[Testinitialize]
        public void initilize()
        {
           Webd= Helper.GetWebDriverC(Chrome); 
        }
[Priority(0)]
        [TestMethod]
        public void 1()
        {
}
[Priority(2)]
        [TestMethod]
        public void 2()
        {
}
     .
     .
     .

[Priority(10)]
            [TestMethod]
            public void 10()
{
}
  

Test初始化中只有一个驱动程序,即chrome和chrome在每个测试用例运行之前打开。我希望当测试用例基于某些条件运行时(如前所述),测试用例在所需的浏览器上运行。 如何使用C#mstest实现该目标?

解决方法

这里的问题是,您在TestInitialize步骤中设置了WebDriver,因此同一类中的所有测试都将使用相同的驱动程序,在本例中为Chrome。

一种方法是为FireFox和Chrome具有单独的测试类。

Chrome测试:

public class ChromeTests
{
  [TestInitialize]
  public void initilize()
  {
    Webd = Helper.GetWebDriverC(Chrome); 
  }

  [TestMethod]
  public void 1()
  {
  }
}

FireFox测试

public class FireFoxTests
{
  [TestInitialize]
  public void initilize()
  {
    Webd = Helper.GetWebDriverFF(Chrome); 
  }

  [TestMethod]
  public void 1()
  {
  }
}

替代解决方案包括:

  • 测试类中有两个WebDriver,一个用于Chrome,一个用于FireFox,然后您可以在测试中决定要使用的驱动程序。

  • 在每个测试中创建一个新的WebDriver实例