How to mock a function from the same Class with moq
Disclaimer: I want to show you what is possible, I strongly recommend not mocking a function from the same class because you should probably extract the function in a different class. But here is a possible solution anyway.
Suppose we have the NumberGenerator class with an interface with two functions and want to moq GetNumberFive, so that the function returns 4. The desired function must be virtual because moq must override the function and this is only possible if you make a function ``virtual` in C#.
Now lets look at the testing code.
We created two NumberGenerator to test our code. When you want to mock a function from the same class, you have to use the _numberGeneratorMock. The trick is to set CallBase true, because it is used to specify whether the base class virtual implementation will be invoked for mocked dependencies.
So our normal tests looks like this:
And our test with _numberGeneratorMock
can look like this:
Here you use the Setup
method as usual (when using moq). And in the act step you need to
acces the Object
from your mocked class which you want to test.