0

Inside the service which is being tested there is the following code:

public SendNotificationAsync(SomeDataType payloadData)
{
    ...

    var androidPayload = new AndroidNotification
    {
        Data = payloadData,
    };
    await _hubClient.SendFcmNativeNotificationAsync(androidPayload, tags);

    ...
}

The _hubClient is an instance of a INotificationHubClient interface which is injected in this service.

The Moq setup for the test is the following:

private readonly Mock<INotificationHubClient> _hubClient = new(MockBehavior.Strict);
public Task TestMethod()
{
    var _notificationService = new NotificationService(_hubClient.object);
    ...

    _hubClient
        .Setup(s => s.SendFcmNativeNotificationAsync(It.Is<AndroidNotification>(a => a == androidPayload), It.Is<string[]>(s => s == stringArray)))
        .ReturnsAsync(retVal)
        .Verifiable();

    ...

    await _notificationService.SendNotificationAsync(payloadData);

    _hubClient.Verify();
}

When I run the tests I get the following error:

Moq.MockException: Mock<INotificationHubClient:1>: This mock failed verification due to the following:
INotificationHubClient s => s.SendFcmNativeNotificationAsync(It.Is<AndroidNotification>(a => a == AndroidNotification), It.Is<string[]>(s => s == ["userName1" , "userName2"])): This setup was not matched.

The tests pass when I use It.IsAny<AndroidNotification>() but I'd like to check the values passed in which is why I prefer a method similar to the one currently used.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Stephanos B.
  • 340
  • 3
  • 15
  • 1
    Moq uses reference equality check on parameters. Since you create a new `androidPayload` variable inside your `SendNotificationAsync` that can't be the same as you pass during the Setup call. – Peter Csala Oct 29 '21 at 10:16
  • Try to capture the method arguments via a `Callback` method. [Related SO topic](https://stackoverflow.com/questions/3269717/moq-how-to-get-to-a-parameter-passed-to-a-method-of-a-mocked-service) – Peter Csala Oct 29 '21 at 10:18

1 Answers1

1

Apparently the error was related to an incorrect reference equality check, the second arg parameter passed in the test was a string[] type while the method needed a IEnumerable<string> to pass since Moq was checking for a specific type in this case.

Stephanos B.
  • 340
  • 3
  • 15