I am trying to mock a Func<Tin, Tout>
using Moq and verify that it is being called (invoked)
the code I currently have is:
var handlers = new List<ICallBridgeHandler>();
var stationIdReader = new Mock<IStationIdReader>();
var loggerCreator = new Mock<Func<Type, ILogger>>();
loggerCreator.Setup(x => x.Invoke(typeof(Service))).Returns<ILogger>(null);
loggerCreator.Verify(x => x.Invoke(It.IsAny<Type>()), Times.Never);
var sut = new Service(stationIdReader.Object, handlers, loggerCreator.Object);
loggerCreator.Verify(x => x.Invoke(typeof(Service)), Times.Once);
Assert.IsNotNull(sut);
but this is blowing up with the exception:
Result StackTrace:
at Moq.ExpressionExtensions.GetCallInfo(LambdaExpression expression, Mock mock)
at Moq.Mock.<>c__DisplayClass1c`2.<Setup>b__1b()
at Moq.PexProtector.Invoke[T](Func`1 function)
at Moq.Mock.Setup[T,TResult](Mock`1 mock, Expression`1 expression, Condition condition)
at Moq.Mock`1.Setup[TResult](Expression`1 expression)
at Tests.ConstructorRetrievesLoggerFromCreator() in ...
Result Message:
Test method Tests.ConstructorRetrievesLoggerFromCreator threw exception:
System.InvalidCastException: Unable to cast object of type
'System.Linq.Expressions.InstanceMethodCallExpressionN' to type
'System.Linq.Expressions.InvocationExpression'.
Can anyone help with this, I need to be able to check that the constructor calls the Func.
N.B. I tried to remove the setup step as I do not care about the return value for this test, and I get the same problem on the Verify call.
Obviously I could inject a concrete Func that returns a given value and interrogate that value in some way, however my Service class looks like:
public class Service
{
private readonly ILogger _logger;
[ImportingConstructor]
public Service([Import("GetLogger")]Func<Type, ILogger> loggerCreator)
{
if (loggerCreator == null)
throw new ArgumentNullException(nameof(loggerCreator));
_logger = loggerCreator.Invoke(GetType());
}
}
So without changing my class I cannot see the member variable _logger
so I have no way to verify that loggerCreator
has been invoked, and that is what I want to verify.