Search code examples
c#moqxunit

Mock.Verify() failed - This setup was not matched?


I have the following test code.

var test = "Test";

var command = new MyCommand { V = test };

var mock = new Mock<IRepository>(); // IRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(p)).Verifiable();

var sut = new C(mock.Object);
var result = await sut.M(command);

mock.Verify();

The test should pass. However, it failed with the error of,

  Message: 
    Moq.MockException : Mock:
    This mock failed verification due to the following:

       IRepository x => x.Save(P):
       This setup was not matched.
  Stack Trace: 
    Mock.Verify()

sut.M() will convert a string X to type P with value of P(X).


Solution

  • It seems to me that you want to verify that the Save method from your mock is called with a specific value, and not just a type.

    I have tried something like the following and believe it should work. I have modified your example.

    var test = "Test";
    
    var command = new MyCommand { V = test };
    
    var mock = new Mock<IRepository>(); // IRepository has the method of Save()
    var p = new P(test);
    mock.Setup(x => x.Save(It.IsAny<P>());
    
    var sut = new C(mock.Object);
    var result = await sut.M(command);
    
    mock.Verify(x => x.Save(It.Is<P>(v => v.Value.Equals(p.Value))), Times.AtLeastOnce);
    

    This tests that the values of the specific property are equal.

    I Tested this with the following test:

    var test = "Test";
    
    var mock = new Mock<ITestRepository>(); // ITestRepository has the method of Save()
    var p = new P(test);
    mock.Setup(x => x.Save(It.IsAny<P>()));
    
    mock.Object.Save(new P(test));
    
    mock.Verify(x => x.Save(It.Is<P>(v => v.Value.Equals(p.Value))), Times.AtLeastOnce);