The mocking library Moq has a Setup() method with the signature:
public ISetup<T, TResult> Setup<TResult>(Expression<Func<T, TResult>> expression)
So I can do something like this just fine (using the library’s recursive mocking):
Mock<Thing> _thing = new Mock<Thing>();
_thing.Setup((Thing t) => t.PropA.SubPropB).Returns(string.Empty);
But this fails:
Expression<Func<Thing, object>> test = (Thing t) => t.PropA.SubPropB;
_thing.Setup(test).Returns(string.Empty);
with the error:
Expression is not a method invocation: t => (Object)t.PropA.SubPropB
What’s the difference between the inlined lambda and the one assigned to a variable first? Aren’t both expression trees and not yet compiled (Moq parses the tree)?
Edit – Looks like the issue is with the Func<Thing, object> typing. Why is, e.g., string acceptable, but object is not?
because function declaration in
moqis not covariant by generic types. Try to Setup moq in next waybecause you have next signature
Expression<Func<Thing, object>>and it’s not covariant with respect toobjectOr change your signature to
stringlike this (assumet.PropA.SubPropBreturns string):Real-case
I have created a test project with
Expressionas local variable, it all works fine withstringandobject. Please check my configuration if I missed something. Moq – 4.0.10827v