Moq setup method failing on callback

Viewed 49

My unit test is failing on setup method

var myMock = new Mock<IMyInterface<IImportLine>>();
        myMock.Setup(m => m.StartExecution(It.IsAny<Func<Stream, IMyInterface<IImportLine>, bool>>(), null))
                     .Callback<Func<Stream, IMyInterface<IImportLine>, bool>>(action => action(null, new IMyInterface<IImportLine>()));

IMyInterface looks like below

public interface IImportTransport<T> where T : IImportLine
{
    void StartExecution(Func<Stream, ImportOperation<T>, bool> processor, string id = null);
}

The error message is System.ArgumentException : Invalid callback. Setup on method with parameters (Func3,String) cannot invoke callback with parameters (Func3).

How do we fix this?

1 Answers

You need to provide an argument to your callback that corresponds to the id parameter (even though you know it'll be null).

myMock.Setup(m => m.StartExecution(It.IsAny<Func<Stream, IImportTransport<IImportLine>, bool>>(), null))
    .Callback<Func<Stream, IImportTransport<IImportLine>, bool>, string>(
        (action, id) => action(null, new ImportOperation<IImportLine>()));

Since you aren't using that parameter, you can use a discard if you like.

myMock.Setup(m => m.StartExecution(It.IsAny<Func<Stream, IImportTransport<IImportLine>, bool>>(), null))
    .Callback<Func<Stream, IImportTransport<IImportLine>, bool>, string>(
        (action, _) => action(null, new ImportOperation<IImportLine>()));
Related