How did I do?*

MoqException: All invocations on the mock must have a corresponding setup

Troubleshoot this common Moq error message when writing tests

Ensure:

  • You've instantiated the mock
var myService = new Mock<IMyService>(Strict);
  • You've called Setup on your instantiation, with arguments which match EXACTLY what will be called during test execution by the real code (all arguments should be specified, even if they're null/default)
myService
    .Setup(s => s.MyMethod(
        "somePreciseString",
        It.IsAny<Guid>(), // Any GUID
        It.IsAny<bool?>(), // Any nullable boolean
        true, // Specific boolean
        null)) // Optional parameter
    .Returns(Task.CompletedTask);
  • Any implementing services include your instantiation
var myComplexService = BuildComplexService(
    myService.Object
    mySecondService.Object
    myThirdService.Object
);
  • All method calls on the mock are verified
mock.VerifyAll();