【问题标题】:Moq Expect On IRepository Passing Expression最小起订量期望 IRepository 传递表达式
【发布时间】:2008-11-13 21:34:00
【问题描述】:

我正在使用此代码来验证我正在测试的方法的行为:

    _repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
    .Returns(new List<JSOFile>())
    .AtMostOnce()
    .Verifiable();

_repository 定义为:

private Mock<IRepository<JSOFile>> _repository;

当我的测试运行时,我得到了这个异常:

不支持表达式 t => (t.STATUS_CD = "A")。

如果我不能将表达式传递给 Expect 方法,谁能告诉我如何测试这种行为?

谢谢!!

【问题讨论】:

    标签: unit-testing moq


    【解决方案1】:

    这有点作弊。我对表达式执行 .ToString() 并比较它们。这意味着您必须在被测类中以相同的方式编写 lambda。如果你愿意,你可以在这一点上做一些解析

        [Test]
        public void MoqTests()
        {
            var mockedRepo = new Mock<IRepository<Meeting>>();
            mockedRepo.Setup(r => r.FindWhere(MatchLambda<Meeting>(m => m.ID == 500))).Returns(new List<Meeting>());
            Assert.IsNull(mockedRepo.Object.FindWhere(m => m.ID == 400));
            Assert.AreEqual(0, mockedRepo.Object.FindWhere(m => m.ID == 500).Count);
        }
    
        //I broke this out into a helper as its a bit ugly
        Expression<Func<Meeting, bool>> MatchLambda<T>(Expression<Func<Meeting, bool>> exp)
        {
            return It.Is<Expression<Func<Meeting, bool>>>(e => e.ToString() == exp.ToString());
        }
    

    【讨论】:

      【解决方案2】:

      浏览起订量讨论列表,我想我找到了答案:

      Moq Discussion

      看来我遇到了 Moq 框架的限制。

      编辑,我找到了另一种测试表达式的方法:

      http://blog.stevehorn.cc/2008/11/testing-expressions-with-moq.html

      【讨论】:

        【解决方案3】:

        在 Rhino Mocks 中你会做这样的事情......

        不要使用 Expect,而是使用 Stub 并忽略参数。然后有--

        Func<JSOFile, bool> _myDelegate;
        
        _repository.Stub(f => FindAll(null)).IgnoreArguments()
           .Do( (Func<Func<JSOFile, bool>, IEnumerable<JSOFile>>) (del => { _myDelegate = del; return new List<JSOFile>();});
        

        调用真实代码

        *设置一个虚假的 JSOFile 对象,将 STATUS_CD 设置为“A”*

        Assert.IsTrue(_myDelegate.Invoke(fakeJSO));
        

        【讨论】:

          【解决方案4】:

          试试这个

           _repository.Expect(f => f.FindAll(It.Is<SomeType>(t => t.STATUS_CD == "A")))
          

          检查错误的一种简单方法是确保在期望调用结束时始终有三个 ')。

          【讨论】:

          • Is 方法返回 T。FindAll 方法采用 Func<...>,所以这不起作用。
          【解决方案5】:

          如果你想测试是否传递了正确的参数,你总是可以“滥用”returns语句:

          bool 正确参数 = true;

          _repository.Expect(f => f.FindAll(It.IsAny>()))

          .Returns((Func func) => {correctParamters = func(fakeJSOFile); return new List-JSOFile-(); })

          .AtMostOnce()

          .Verifiable();

          Assert.IsTrue(正确参数);

          这将使用您想要的参数调用传入的函数。

          【讨论】:

            猜你喜欢
            • 2021-01-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-09-22
            • 1970-01-01
            • 2019-12-03
            • 2011-09-12
            • 1970-01-01
            相关资源
            最近更新 更多