Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression<Func<T, bool>> with It.IsAny always return true

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?

like image 974
Johan Nordin Avatar asked Nov 16 '12 22:11

Johan Nordin


1 Answers

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));
like image 181
moribvndvs Avatar answered Nov 08 '22 09:11

moribvndvs