You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium C#中复用foreach循环函数及调用工具类方法

提取可复用的Residency筛选方法并在测试代码中调用

第一步:在Utilities类中封装筛选逻辑

把你原来的循环逻辑封装成静态工具方法,确保全局可复用:

public static class Utilities
{
    // 筛选指定TestGuid且StartDate最晚的Residency
    public static Residency? GetLatestResidencyByTestGuid(IEnumerable<Residency> residencies, Guid testGuid)
    {
        Residency? latestResidency = null;
        foreach (Residency residency in residencies)
        {
            if (residency.TestGuid == testGuid)
            {
                // 首次匹配或当前项日期更新时替换结果
                if (latestResidency == null || residency.StartDate > latestResidency.StartDate)
                {
                    latestResidency = residency;
                }
            }
        }
        return latestResidency;
    }
}

第二步:在测试代码中调用该方法

假设你的测试代码里已有Test实例test和目标testGuid,直接调用工具方法即可:

// 调用工具方法获取目标Residency
Residency? targetResidency = Utilities.GetLatestResidencyByTestGuid(test.Residencies, testGuid);

// 按需编写测试断言
// 例1:断言存在符合条件的Residency
Assert.IsNotNull(targetResidency, "未找到匹配TestGuid的Residency");

// 例2:验证属性正确性
Assert.AreEqual(testGuid, targetResidency.TestGuid);
// 额外验证是否为最晚日期
var allMatches = test.Residencies.Where(r => r.TestGuid == testGuid);
foreach (var residency in allMatches)
{
    Assert.IsTrue(residency.StartDate <= targetResidency.StartDate);
}

可选:用LINQ简化实现

如果项目允许使用LINQ,可以用更简洁的写法实现相同逻辑:

public static class Utilities
{
    public static Residency? GetLatestResidencyByTestGuid(IEnumerable<Residency> residencies, Guid testGuid)
    {
        return residencies
            .Where(r => r.TestGuid == testGuid)
            .OrderByDescending(r => r.StartDate)
            .FirstOrDefault();
    }
}

内容的提问来源于stack exchange,提问作者user21175930

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:57:13