IRepository传递表达式上的最小期望量

问题描述 投票:9回答:5

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

    _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
5个回答
2
投票

这有点作弊。我对表达式执行.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());
    }

1
投票

浏览Moq讨论列表,我想我找到了答案:

Moq Discussion

似乎我遇到了Moq框架的局限。

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

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


0
投票

在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>();});

调用真实代码

**将STATUS_CD设置为“ A”的伪JSOFile对象*

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

0
投票

尝试一下

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

检查错误的一种简便方法是确保在期望呼叫结束时您始终具有三个')。


0
投票

如果要测试是否传递了正确的参数,则始终可以“滥用” returns语句:

bool correctParamters = true;

_ repository.Expect(f => f.FindAll(It.IsAny>()))

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

。AtMostOnce()

。Verifiable();

Assert.IsTrue(correctParamters);

这将调用传递给您所需参数的函数。

© www.soinside.com 2019 - 2024. All rights reserved.