Setting up methods with lambda expressions
I am trying to fake a method on an instance using the lambda expression of the corresponding correspondent:
private void TranslateCallbackToSetup<TResult>(Mock<TService> stubService, IMethodCall<TService,TResult> methodCall)
{
stubService.Setup(t => methodCall.RunMethod(t)).Returns(() =>
{
return default(TResult);
});
}
public interface IMethodCall<in TService, out TResult> : IMethodCall where TService : class
{
Func<TService, TResult> RunMethod { get; }
}
The syntax seems fine, but the code doesn't work with the ArgumentException:
Expression is not a method call: t => t
Any thoughts?
source to share
It doesn't work because you are trying to set the method to something other than the layout itself.
You say you want your instance to IMethodCall
return a specific value when its method RunMethod
is called with yours stubService
as a parameter. In this case, you will need to pass mock IMethodCall
, since this is the object whose behavior you define.
If you look at the examples here , you can see that all the methods that mock are layout methods. So if you can refactor your TService type to use the Call method instead, you can make it work.
On your service
public IService
{
TResult ExecuteMethodCall(IMethodCall<IService, TResult>);
}
and then in your test
stubService.Setup(t => t.ExecuteMethodCall(methodCall))
source to share