Ok right, I'm trying to learn a bit about Moq and something puzzles me.
I can setup a verify method to check if a method has been called, and this works perfectly. But I'd like to try something else:
So, this is fine:
mockNoteContext.Verify(ctx => ctx.SaveChanges(), Times.Once);
But I try to stretch it a bit to do more checks:
mockNoteContext.Verify(ctx => ctx.Notes.Count() == 1);
Doesn't work, so I started playing around a bit and got the following:
Expression<Func<NoteContext, bool>> expr = ctx => ctx.Notes.Count() == 1;
mockNoteContext.Verify(It.Is<Expression<Func<NoteContext, bool>>>(e => e == expr));
Which just gives a null value exception. But I don't understand why. Probably it doesn't know what to do with 'e'?. This all feels clunky to boot. How can I set this up properly?
Of course I know I can just read:
var noteCount = mockNoteContext.Object.Notes.Count();
And Assert with that, but I'm just curious how I could leverage Verify to handle this for me :)
Any help is welcome!
That is not how to use the Verify call. It is used to verify if a member on the mock was invoked. Not to assert values.
Review the documentation https://github.com/Moq/moq4/wiki/Quickstart#verification
What you suggested at the end of your question is the advised way to assert values.
var expected = 1;
var noteCount = mockNoteContext.Object.Notes.Count();
Assert.AreEqual(expected, noteCount);
Reference Moq Quickstart to get a better understanding of how to use the mocking framework.
There are also libraries that are used specifically for assertions.
One such library is Fluent Assertions
Fluent Assertions is a set of .NET extension methods that allow you to more naturally specify the expected outcome of unit tests.
for example
var expected = 1;
var noteCount = mockNoteContext.Object.Notes.Count();
noteCount.Should().Be(expected); //<-- fluent assertion
The two libraries can be used together to help when testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With