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!!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With