Moq: Invalid callback. Setup on method with parameters cannot invoke callback with parameters

℡╲_俬逩灬. 提交于 2019-12-05 10:40:23

问题


I am trying to use moq to write a unit test. Here is my unit test code

        var sender = new Mock<ICommandSender>();
        sender.Setup(m => m.SendCommand(It.IsAny<MyCommand>(), false))
              .Callback(delegate(object o)
              {
                  var msg = o as MyCommand;
                  Assert.AreEqual(cmd.Id, msg.Id);
                  Assert.AreEqual(cmd.Name, msg.Name);
              })
              .Verifiable();

SendCommand takes an object and optional boolean parameter. And MyCommand derives from ICommand.

void SendCommand(ICommand commands, bool idFromContent = false);

When the test runs, I see the error

System.ArgumentException : Invalid callback. Setup on method with parameters (ICommand,Boolean) cannot invoke callback with parameters (Object).

I want to check if the content of the message is what I sent in. I searched the forum and found a couple of different variations of this issue, but those didn't help. Any help is greatly appreciated.


回答1:


You need to call the generic overload of Callback with the specific types expected by the method. The following should work:

sender.Setup(x => x.SendCommand(It.IsAny<MyCommand>(), false))
      .Callback<ICommand, bool>((command, idFromContent) =>
          {
              var myCommand = command as MyCommand;
              Assert.That(myCommand, Is.Not.Null);
              Assert.That(myCommand.Id, Is.EqualTo(cmd.Id));
              Assert.That(myCommand.Name, Is.EqualTo(cmd.Name));
          })
      .Verifiable();

If the assertions fail in the callback then the test fails immediately, so the call to Verifiable() (and presumably the subsequent call to Verify()) seems to be redundant. If you want to allow the mocked Send invocation to proceed even if it does not meet the criteria and then verify it after the fact, then you can do this instead (after the tested method is invoked):

sender.Verify(x => x.SendCommand(It.Is<MyCommand>(c => 
    {
        Assert.That(c, Is.Not.Null);
        Assert.That(c.Id, Is.EqualTo(cmd.Id));
        Assert.That(c.Name, Is.EqualTo(cmd.Name));
        return true;
    }), false), Times.Once());


来源:https://stackoverflow.com/questions/18927609/moq-invalid-callback-setup-on-method-with-parameters-cannot-invoke-callback-wi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!