Moq可以忽略传递给函数的参数数量吗?

时间:2013-09-18 11:42:42

标签: c# moq

我正在尝试使用Moq我的通用存储库。我有一个名为SingleOrDefaultIncluding的方法,如下所示:

T SingleOrDefaultIncluding(Expression<Func<T, bool>> wherePredicate, params Expression<Func<T, object>>[] includes);

现在在我的单元测试中,我设置了Moq,如下所示:

 _agreementRepositoryMock.Setup(m => m.SingleOrDefaultIncluding
                                                (
                                                    It.IsAny<Expression<Func<Agreement, bool>>>(),
                                                    It.IsAny<Expression<Func<Agreement, object>>>(),
                                                    It.IsAny<Expression<Func<Agreement, object>>>()
                                                )
            ).Returns(AgreementMocks.GetOne());

我可以以某种方式指定传递给SingleOrDefaultIncluding它的任何参数应该返回我的协议吗?为了完成这项工作,我必须确保准确传递3个参数,就像我正在测试的方法一样。或者我可以以某种方式将数组传递给Moq吗?

1 个答案:

答案 0 :(得分:1)

也许使用您不“展开”params的表单?类似的东西:

_agreementRepositoryMock.Setup(m => m.SingleOrDefaultIncluding
  (
    It.IsAny<Expression<Func<Agreement, bool>>>(),
    It.IsAny<Expression<Func<Agreement, object>>[]>()
  )
  ).Returns(AgreementMocks.GetOne());

请注意上面的[]。未经测试。

如果我误解了,要冻结参数的数量,也许可以尝试:

_agreementRepositoryMock.Setup(m => m.SingleOrDefaultIncluding
  (
    It.IsAny<Expression<Func<Agreement, bool>>>(),
    It.Is<Expression<Func<Agreement, object>>[]>(array => array.Length == 2)
  )
  ).Returns(AgreementMocks.GetOne());

使用It.Is<>而不是It.IsAny<>