Moq Expect On IRepository Passing Expression

时光怂恿深爱的人放手 提交于 2019-11-29 18:46:57

问题


I am using this code to verify a behavior of a method I am testing:

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

_repository is defined as:

private Mock<IRepository<JSOFile>> _repository;

When my test is run, I get this exception:

Expression t => (t.STATUS_CD = "A") is not supported.

Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?

Thanks!!


回答1:


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



回答2:


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




回答3:


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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/288413/moq-expect-on-irepository-passing-expression

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