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

使用VerifyTests库时,能否忽略特定DateTime字段的清理操作?

针对Verify测试库:仅禁用特定日期属性的清理

可以,你可以通过以下几种方式实现仅保留对象中特定日期属性、清理其他日期属性的需求:

方法1:通过AddScrubber自定义清理规则(临时单测试场景)

如果只是在单个测试中需要保留特定日期属性,可以直接添加自定义清理逻辑,判断属性路径并跳过目标属性的清理:

假设你有如下测试对象:

public class Order
{
    public DateTime CreatedAt { get; set; } // 需要保留的日期属性
    public DateTime UpdatedAt { get; set; } // 需要清理的日期属性
    public string OrderNumber { get; set; }
}

测试代码示例:

await Verify(order)
    .AddScrubber(context =>
    {
        // 跳过对CreatedAt属性的清理
        if (context.Path.EndsWith(nameof(Order.CreatedAt)))
        {
            return null;
        }

        // 对其他日期属性执行默认的清理逻辑
        if (context.Value is DateTime dateTime)
        {
            return VerifyScrubbers.DefaultDateTimeScrubber(dateTime);
        }

        return null;
    });

方法2:先禁用全局日期清理,再手动清理指定属性

另一种思路是先调用DontScrubDateTimes()关闭全局日期清理,再针对需要清理的属性单独添加规则:

await Verify(order)
    .DontScrubDateTimes()
    .AddScrubber(context =>
    {
        // 仅清理UpdatedAt属性
        if (context.Path.EndsWith(nameof(Order.UpdatedAt)) && context.Value is DateTime)
        {
            return "scrubbed-date"; // 或者使用Verify默认的日期清理格式
        }

        return null;
    });

方法3:使用自定义特性标记(复用场景)

如果多个测试或多个对象都需要保留特定日期属性,可以定义一个自定义特性,结合清理器实现规则复用:

  1. 定义特性:
[AttributeUsage(AttributeTargets.Property)]
public class KeepOriginalDateAttribute : Attribute { }
  1. 在对象中标记目标属性:
public class Order
{
    [KeepOriginalDate]
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string OrderNumber { get; set; }
}
  1. 测试中使用特性判断的清理器:
await Verify(order)
    .AddScrubber(context =>
    {
        var property = context.GetProperty();
        // 跳过带有KeepOriginalDate特性的属性
        if (property != null && property.GetCustomAttribute<KeepOriginalDateAttribute>() != null)
        {
            return null;
        }

        // 其他日期属性执行默认清理
        if (context.Value is DateTime dateTime)
        {
            return VerifyScrubbers.DefaultDateTimeScrubber(dateTime);
        }

        return null;
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:52:58