检查Moq中设置的表达式输入参数

3

我想模拟一个类似于这样的方法:

OrderAttrTypeRepository.Get(attributeType => attributeType.Description == property.Key);

我希望能根据属性.Key比较该方法的调用参数。

我尝试了以下方法:

 Expression<Func<OrderAttrType, bool>> saveObject;
 Expression<Func<OrderAttrType, bool>> criteria = y => y.Description == "ServiceCharge";
 Mock.Setup(x => x.OrderAttrTypeRepository.Get(It.IsAny<Expression<Func<OrderAttrType, bool>>>()))
 .Callback<Expression<Func<OrderAttrType, bool>>>(i => saveObject = i)
 .Returns<Expression<Func<OrderAttrType, bool>>>(filter =>
  {
   if (Utility.ExpressionComparer.AreEqual(filter, criteria))
      return "Whatever";
   else
      return null;
  })

当我运行测试时,无论如何都会得到一个null。即使方法被调用且property.key = "ServiceCharge"。

在saveObject对象中,表达式主体看起来像这样:

attributeType.Description == value(Quipu.Eba.Service.UtilityPaymentService+<>c__DisplayClass53).property.Key)

这就是表达式不被视为相同的原因。有什么建议吗?

OrderAttrTypeRepository.Get 是如何声明的? - Holstebroe
它是接口的一部分,看起来像 T Get(Expression<Func<T, bool>> expression)。内部声明对问题并不重要。 - lpaloub
1个回答

1

我现在已经找到问题的答案。

property.Key 是一个变量,因此,在作为表达式进行评估时,它会被转换为 value(Quipu.Eba.Service.UtilityPaymentService+<>c__DisplayClass53).property.Key)

如果 property.key 是一个具有值为 "ServiceCharge" 的常量字符串,那么它将按预期进行转换,并且我将能够比较这些表达式。

因此,我必须以另一种方式解决问题,因为无论变量 property.key 的值是什么,它始终被转换为其引用而不是值,这意味着据我所知,我无法区分这些表达式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接