Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to return the same value in moq mocking?


Asked by Caroline Stephenson on Dec 08, 2021 FAQ



The Returns method has lots of overloads. Currently you are using the one with the signature Returns (TResult) where you can specify the value to return and Moq use the same value every time the mocked method is called (so you get the same instance of your SkuCountByRetailerVm.
Indeed,
This isolates the code you’re testing, ensuring that it works on its own and that no other code will make the tests fail. With mocks, you can set up the object, including giving parameters and return values on method calls and setting properties. You can also verify that the methods you set up are being called in the tested code.
Keeping this in consideration, The DateTime.Now.Ticks property is evaluated when creating the expectation so the mock object will always return the same value. We can see this by executing the method twice and outputting the results:
Consequently,
Moq offers several utilities to properly configure method calls. As shown earlier, methods can be configured using the Setup method. Additionally, developers can configure sequences of calls. Finally, Moq supports the configuration of methods with less common arguments such as reference parameters, out parameters and optional arguments.
And,
Sometimes when doing unit test, we encounter subsequent calls to the same method. When mocking a method the default behavior is to always return the same result. In this post, I will show how you can mock multiple calls to the same method with the mocking frameworks FakeItEasy, Moq and NSubstitute.