Selenium Grid多测试用例并行执行异常问题咨询(C#)
解决C# Selenium Grid测试并行执行的问题
你现在的核心问题是测试框架本身没启用并行执行——哪怕Grid有多个Node,测试还是一个接一个跑,手动拆项目或开VS会话确实太折腾。咱们直接从测试框架配置和代码优化入手解决:
第一步:选支持并行的C#测试框架
C#里的xUnit和NUnit都原生支持并行测试,这是实现你需求的基础,下面分别给出两种框架的具体配置方法:
用xUnit实现并行
- 添加并行配置文件
在测试项目根目录创建xunit.runner.json文件,设置并行参数(对应你的2个Node节点):
{ "parallelizeTestCollections": true, "maxParallelThreads": 2, "parallelizeAssembly": true }
记得把这个文件的「复制到输出目录」设置为「如果较新则复制」,确保测试运行器能读取到配置。
- 编写独立的测试代码
每个测试方法必须创建独立的RemoteWebDriver实例,这样每个测试会单独向Grid Hub请求分配Node:
using Xunit; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Remote; public class ParallelSeleniumTests { [Fact] public void TestCase1() { var chromeOptions = new ChromeOptions(); // 替换成你的Grid Hub地址 using var driver = new RemoteWebDriver(new Uri("http://your-hub-ip:4444/wd/hub"), chromeOptions); driver.Navigate().GoToUrl("https://your-test-site.com"); // 你的测试逻辑 Assert.True(driver.Title.Contains("预期标题")); } [Fact] public void TestCase2() { var chromeOptions = new ChromeOptions(); using var driver = new RemoteWebDriver(new Uri("http://your-hub-ip:4444/wd/hub"), chromeOptions); driver.Navigate().GoToUrl("https://your-test-site.com"); // 第二个测试的逻辑 Assert.Equal("预期文本", driver.FindElement(By.Id("target-element")).Text); } }
用NUnit实现并行
- 添加并行属性
在测试类或测试方法上标记[Parallelizable]属性,指定并行范围:
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Remote; [TestFixture] [Parallelizable(ParallelScope.Children)] // 让类内的测试方法并行执行 public class ParallelSeleniumTests { [Test] public void TestCase1() { var chromeOptions = new ChromeOptions(); using var driver = new RemoteWebDriver(new Uri("http://your-hub-ip:4444/wd/hub"), chromeOptions); // 测试逻辑 } [Test] public void TestCase2() { var chromeOptions = new ChromeOptions(); using var driver = new RemoteWebDriver(new Uri("http://your-hub-ip:4444/wd/hub"), chromeOptions); // 测试逻辑 } }
- 配置NUnit并行参数
在项目的nunit.config文件里设置最大并行线程数:
<configuration> <nunit> <test-runner> <parallelize workers="2" /> </test-runner> </nunit> </configuration>
关键注意事项
- 测试必须完全独立:绝对不能在测试之间共享WebDriver实例、数据文件或其他资源,否则并行时会出现冲突或奇怪的错误。
- 检查Grid Node配置:确保每个Node的
maxSession设置为至少1(默认就是1),这样Hub才能同时给每个Node分配一个测试任务。 - TeamCity适配:在TeamCity中运行时,要给测试运行器开启并行选项——比如xUnit步骤勾选「允许并行测试执行」,NUnit步骤添加
--workers=2参数。
这样配置后,测试框架会同时启动多个测试,每个测试向Grid Hub请求资源,Hub会自动把它们分配到不同的Node上,完美实现你想要的并行效果,再也不用手动拆项目啦。
内容的提问来源于stack exchange,提问作者JumpIntoTheWater
相关产品推荐
相关产品推荐

