Expression> with It.IsAny always return true

c# expression-trees generics moq unit-testing

Question

I'm trying to create a generic testclass to test my generic controllers. Everything is working fine except this: I have a method like this:

private T GetSingle(Expression<Func<T, bool>> expression)

I'm trying to setup the test like so:

var Guids = new[] { Guid.NewGuid(), Guid.NewGuid() };
var items = Guids.Select(x => new T {Id = x});
var mock = new Mock<IRepository<T>>();
mock.Setup(m => m.GetSingle(
    It.IsAny<Expression<Func<T, bool>>>()))
   .Returns(new T());

And execute the test like this:

var value = Repository.GetSingle(x=> x.Id == Guid.NewGuid());

This always return a new T.

Is my setup wrong?

Accepted Answer

You're instructing Moq to return the same exact instance (in this case, new T()), any time GetSingle is invoked, regardless of the expression provided. What you actually want is for it to invoke that expression against items:

mock.Setup(m => m.GetSingle(It.IsAny<Expression<Func<T, bool>>>()))
   .Returns<Expression<Func<T, bool>>>(expression => items.AsQueryable().Single(expression));


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow