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?
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));
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