Moq verify with ItAny not matching as expected

Viewed 61

I'm facing this error

[xUnit.net 00:00:03.08]       Moq.MockException : 
[xUnit.net 00:00:03.08]       Expected invocation on the mock at least once, but was never performed: s => s.Create(ContactScore, It.IsAny<IDbConnection>())
[xUnit.net 00:00:03.08]       
[xUnit.net 00:00:03.08]       Performed invocations:
[xUnit.net 00:00:03.08]       
[xUnit.net 00:00:03.08]          Mock<ContactScoreRepo:1> (s):
[xUnit.net 00:00:03.08]       
[xUnit.net 00:00:03.08]             ContactScoreRepo.Create(ContactScore, NpgsqlConnection)
[xUnit.net 00:00:03.08]       

I guess my problem is that NpgsqlConnection is not matching It.IsAny<IDbConnection>() but I'm not sure,

My verification

            var scoreCreated = new ContactScore
            {
                CampaignId = 1,
                TokenId = 1,
                ContactId = 1,
                Score = 1,
                DebtorId = 1,
            };
            scoreRepo.Verify(s => s.Create(scoreCreated, It.IsAny<IDbConnection>()));

And the actual code calling the method

            await ScoreRepo.Create(new ContactScore
            {
                CampaignId = (int)campaign.Id,
                TokenId = token.Id,
                ContactId = (int)contact.Id,
                Score = req.Score,
                DebtorId = req.DebtorId,
            }, conn);

Where conn is an NpgsqlConnection

I'm very new to Moq (and C# in general) and read the docs https://github.com/Moq/moq4/wiki/Quickstart but can't figure out what I'm suppose to do to fix this error. What I'm missing?

1 Answers

The verification in the example is using a specific instance (reference) of a ContactScore, which is not the instance (reference) used during the invocation.

Use It.Is<>() with a predicate to match the desired properties values of the argument.

scoreRepo.Verify(s => s.Create(It.Is<ContactScore>(s => s.CampaignId == 1 &&
        TokenId == 1 &&
        ContactId == 1 &&
        Score == 1 &&
        DebtorId == 1
     ), 
    It.IsAny<IDbConnection>()));   

Reference Matching Arguments

Related