如何优化Selenium测试中配置变量与DateTime拼接的重复调用逻辑
优化Selenium测试中配置与日期拼接的实现方案
问题根源分析
- 将配置变量设为
private static报错:静态变量初始化阶段,类实例尚未创建,无法访问实例级的_configuration对象,导致无法正确读取配置值。 - 使用get/set属性出现非空问题:未在配置加载环节做非空校验,或属性在配置未完成初始化时被提前访问,最终拼接出含
null的无效字符串。
可行优化方案
方案1:构造函数注入+只读属性(推荐)
通过构造函数注入配置对象,在实例化时完成配置读取、非空校验与字符串拼接,后续直接访问只读属性即可,无需重复调用方法。
using Microsoft.Extensions.Configuration; public class YourTestClass { // 私有只读变量存储配置值与日期 private readonly string _serviceName; private readonly string _vendorName; private readonly string _relationshipManager; private readonly string _thisDay; // 只读属性,直接返回预拼接好的结果 public string NewVendorName { get; } public string NewServiceName { get; } // 构造函数注入IConfiguration,完成初始化 public YourTestClass(IConfiguration configuration) { // 读取配置并做非空校验,避免后续空值问题 _serviceName = configuration[$"{Configuration.EnvConfig}:NewService"] ?? throw new InvalidOperationException("配置项NewService未找到或为空"); _vendorName = configuration[$"{Configuration.EnvConfig}:NewVendor"] ?? throw new InvalidOperationException("配置项NewVendor未找到或为空"); _relationshipManager = configuration[$"{Configuration.EnvConfig}:RelationshipManager"] ?? throw new InvalidOperationException("配置项RelationshipManager未找到或为空"); _thisDay = Configuration.currentDate.ToString(); // 一次性完成字符串拼接,赋值给只读属性 NewVendorName = $"{_thisDay}{_vendorName}"; NewServiceName = $"{_thisDay}{_serviceName}"; } }
优势:
- 配置读取与拼接仅在实例化时执行一次,性能最优;
- 非空校验提前拦截配置缺失问题,避免后续测试失败;
- 只读属性保证值不会被意外修改,符合测试数据的稳定性要求。
方案2:懒加载只读属性
如果部分拼接后的字符串可能不会被用到,可以用懒加载方式,第一次访问属性时才执行拼接逻辑:
using Microsoft.Extensions.Configuration; public class YourTestClass { private readonly string _serviceName; private readonly string _vendorName; private readonly string _thisDay; // 缓存拼接结果的私有变量 private string _newVendorName; private string _newServiceName; public string NewVendorName { get { if (_newVendorName == null) { _newVendorName = $"{_thisDay}{_vendorName}"; } return _newVendorName; } } public string NewServiceName { get { if (_newServiceName == null) { _newServiceName = $"{_thisDay}{_serviceName}"; } return _newServiceName; } } public YourTestClass(IConfiguration configuration) { _serviceName = configuration[$"{Configuration.EnvConfig}:NewService"] ?? throw new InvalidOperationException("配置项NewService未找到或为空"); _vendorName = configuration[$"{Configuration.EnvConfig}:NewVendor"] ?? throw new InvalidOperationException("配置项NewVendor未找到或为空"); _thisDay = Configuration.currentDate.ToString(); } }
优势:
- 仅在需要时执行拼接,节省不必要的计算;
- 同样保证配置的非空校验,避免无效数据。
使用说明
在测试代码中,只需实例化YourTestClass(依赖注入框架会自动注入IConfiguration),之后直接访问NewVendorName和NewServiceName属性即可,无需重复调用方法:
var testClass = new YourTestClass(_configuration); // 直接使用属性填充表单或验证 driver.FindElement(By.Id("VendorName")).SendKeys(testClass.NewVendorName);
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

