Home > Software design >  Moq setup method failing on callback
Moq setup method failing on callback

Time:06-10

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?

CodePudding user response:

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

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, id) => action(null, new IMyInterface<IImportLine>()));

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

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>()));
  • Related