Skip to main content
 首页 » 编程设计

c#之验证采集通过

2024年02月13日9itcoder

我正在尝试验证一个复杂的集合是否已传递到一个方法中。

我似乎想不出如何编写 lambda 来进行测试。

这是我正在尝试做的事情的简化版本:

var parameters = new List<NotificationParameter>() 
{ 
    new NotificationParameter() 
    { 
        Key = "photoShootId", 
        Value = 1, 
    }, 
}; 
 
message.Verify(m => m.Load(It.Is<List<NotificationParameter>>( 
        p => // ??? Ensure that 'p' and 'parameters' have 
             //     the same elements and values for 'Key' and 'Value' 
    ) 
)); 

只是路过parameters至 verify测试失败,所以我想针对 Key 进行测试和 Value属性。

p上面的类型是 List<NotificationParameter> .

请您参考如下方法:

您可以使用 .All 对每个元素执行一个表达式,如果所有元素都返回 true,则返回 true,因此对于您的特定情况,我们可以将条件写为

message.Verify(m => m.Load(It.Is<List<NotificationParameter>>( 
   pList => pList.All(p => parameters.Any(pTest => p.Key == pTest.Key &&  p.Value == pTest.Value)) 
    ) 
)); 

其他方法是使用 IEqualityComparer & SequenceEqual

例如

class NotificationParameterComparer : IEqualityComparer<NotificationParameter> 
{ 
    public bool Equals(NotificationParameter x, NotificationParameter y) 
    { 
        if(x==null || y == null) 
            return false; 
        return x.Key == y.Key && x.Value == y.Value 
    } 
 
    public int GetHashCode(NotificationParameter parameter) 
    { 
        if (Object.ReferenceEquals(parameter, null)) return 0; 
 
        int hashKey = parameter.Key == null ? 0 : parameter.Key.GetHashCode(); 
 
        int hashValue = parameter.Value.GetHashCode(); 
 
        return hashKey ^ hashValue; 
    } 
} 

然后将其用作

message.Verify(m => m.Load(It.Is<List<NotificationParameter>>( 
    pList => pList.SequenceEqual(parameters, new NotificationParameterComparer()) 
    ) 
));