简体   繁体   中英

Setting up methods by using lambda expressions

I'm trying to fake a method on an instance by using a correspondent lambda expression:

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 to be fine, yet the code fails with an ArgumentException:

Expression is not a method invocation: t => t

Any thoughts?

This is failing because you're trying to set up a method on something other than the mock itself.

You're saying you want your IMethodCall instance to return a certain value when its RunMethod method is called with your stubService as a parameter. In that case you'd need to pass in a mock IMethodCall , as this is object whose behaviour you are defining.

If you look at the examples here , you'll see that all the methods that are being mocked are methods on the mock. So if you could refactor your TService type to take a methodCall instead, you might get it to work.

On your service

public IService 
{
     TResult ExecuteMethodCall(IMethodCall<IService, TResult>);
}

and then in your test

stubService.Setup(t => t.ExecuteMethodCall(methodCall))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM