Reputation: 241
I'm trying to mock a database so that I can verify that the save method was called. I have a project which saves to a database, it takes a list of the objects to save, and a connection string.
this._database.Save<Constraint>(constraints, "DEFAULT");
When I debug I can see that the test successfully goes into my project with a mocked database, and that it hits the save line exactly once.
In my test project I create an instance of the class calling the save method, create and create a mock database, and use .Setup for the save method.
private Mock<IDatabase> _mockDatabase;
...
_mockDatabase = new Mock<IDatabase>();
_mockDatabase.Setup(d => d.Save<Types.Constraint>(It.IsAny<Types.Constraint>(), It.IsAny<String>()));
Then in my test method, I call .Verify to make sure that save was called one time.
_mockDatabase.Verify(d => d.Save<Constraint>(It.IsAny<Constraint>(), It.IsAny<String>()), Times.Once);
However the test fails on this verify. Does anyone know how I can fix this? Thanks for any help/ideas!
Moq.MockException:
Expected invocation on the mock once, but was 0 times: d => d.Save(It.IsAny(), It.IsAny())Configured setups:
d => d.Save(It.IsAny(), It.IsAny()), Times.NeverPerformed invocations:
IDatabase.Save(System.Collections.Generic.List`1[Types.Constraint], "DEFAULT")
Upvotes: 0
Views: 5018
Reputation: 13409
It is calling the save method with a List<Constraint>
instead of just Constraint
, that's why it's failing. You can either change the expected input or verify your code before calling the Save
Upvotes: 1
Reputation: 4222
With your code, what you sending is a List<Constraint>
and you are expecting is a Constraint
so:
Change the setup to :
_mockDatabase.Setup(d => d.Save<Constraint>(It.IsAny<List<Constraint>>(), It.IsAny<String>()));
and Verify to :
_mockDatabase.Verify(d => d.Save<Constraint>(It.IsAny<List<Constraint>>(), It.IsAny<String>()), Times.Once);
Upvotes: 2