Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq Expect On IRepository Passing Expression

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!!

like image 366
Steve Horn Avatar asked Nov 13 '08 21:11

Steve Horn


2 Answers

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());
    }
like image 149
mcintyre321 Avatar answered Oct 22 '22 17:10

mcintyre321


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

like image 25
Steve Horn Avatar answered Oct 22 '22 17:10

Steve Horn