When writing unit tests you will be using dependency injection and writing your classes to interfaces. If you want to test that a certain method was called (or in some instances NOT called) you will need to use a mocking library. When writing C#, Moq is a great tool. Moq provides a method called Verify() that will allow you to test if a mocked object has been used in an expected way. In this tutorial, I will show you have verify() works 💥💥💥

Validating a method gets called: To check if a property on a mocked object has been called, you would write the following snippet:

When this test is executed, if SetCookie isn't called then an exception will be thrown.

Validating a method is NOT called: On the flip side of the coin, sometimes we want to ensure that something is never called. For example, if an object is null the save method should never be made. Moq does not have a NotVerify() method. Instead, you can use an enum called 'Times'. 'Times' can be passed in as a second parameter into Verify(). 'Times' defines how many times the code should be called while the test executed. Times, comes with a Never option. T make sure that a mocked object never gets called, this code could be used:

You now have a way to validate if a mock has or has not been called with a test is executing. Happy Coding 🤘