Setup a method on a mock which has a parameter which is an async function expression

33 views Asked by At

I have a relatively simple interface to mock for which i want to setup the Run method:

public interface IRunner
{
    T Run<T>(ILogger log, ExecutionContext context, Func<FunctionContext, T> func);
}

When it gets invoked it looks something like:

myRunner.Run(myLog, myContext, async ctx => {
  await _do(myContext, myLog, trxData);
});

I have been trying to mock it this way:

var mockRunner = new Mock<IRunner>();
mockRunner.Setup(
  x => x.Run(
    It.IsAny<ILogger>,
    It.IsAny<ExecutionContext>,
    It.IsAny<Func<FunctionContext,T>>
  ));

But the compiler is not happy with that:

The type arguments for method 'IRunner.Run<T>(ILogger,ExecututionContext,Func<FunctionContext,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I'm completely stumped on this and very grateful for any ideas or advice.

1

There are 1 answers

0
Kent Prince On BEST ANSWER

Run method of the IRunner interface is generic, and the type T, you need to provide explicit type arguments to the method you're setting up.

I've assumed that T is Task since you mentioned using await in the lambda passed to Run.

It.IsAny<Func<FunctionContext, Task>>(), specifies a function that takes a FunctionContext and returns a Task.

For example, if Run should return a Task, you should set up the mock to return an instance of Task

mockRunner.Setup(
  x => x.Run<Task<ResultType>>(
    It.IsAny<ILogger>(),
    It.IsAny<ExecutionContext>(),
    It.IsAny<Func<FunctionContext, Task<ResultType>>>()
  )
).ReturnsAsync(new ResultType());