views:

682

answers:

5

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

A: 

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

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.

flukus
The Is Method returns T. The FindAll method takes a Func<...>, so this will not work.
Steve Horn
A: 

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.

flukus
A: 

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

Steve Horn
A: 

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