Moq Expect On IRepository Passing Expression

放肆的年华 提交于 2019-11-30 13:04:56

This is a bit of a cheaty way. I do a .ToString() on the expressions and compare them. This means you have to write the lambda the same way in the class under test. If you wanted, you could do some parsing at this point

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

Browsing the Moq discussion list, I think I found the answer:

Moq Discussion

It appears I have run into a limitation of the Moq framework.

Edit, I've found another way to test the expression:

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

In Rhino Mocks you would do something like this...

Instead of using an Expect, use a Stub and Ignore the arguments. Then have --

Func<JSOFile, bool> _myDelegate;

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

Call Real Code

*Setup a fake JSOFile object with STATUS_CD set to "A" *

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

Try This

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

An easy way to check for errors is to make sure at the end of an expect call you always have three ')'s.

If you want to test the correct parameter is passed you could always "abuse" the returns statement:

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);

This will invoke the function passed in with the arguments you want.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!