Search code examples
c#unit-testingmoq

Unit test to verify that a base class method is called


I have a base class:

public abstract class MyBaseClass
{
    protected virtual void Method1()
    {    
    }
} 

and a derived class:

public class MyDerivedClass : MyBaseClass
{
    public void Method2()
    {
        base.Method1();
    }
}

I want to write a unit test for Method2 to verify that it calls Method1 on the base class. I'm using Moq as my mocking library. Is this possible?

I came across a related SO link:

Mocking a base class method call with Moq

in which the 2nd answer suggests it can be achieved by setting CallBase property to true on the mock object. However it's not clear how this would enable the call to the base class method (Method1 in the above example) to be verified.

Appreciate any assistance with this.


Solution

  • Unit tests should verify behavior, not implementation. There are several reasons for this:

    • The results are the goal, not how you get the results
    • Testing results allows you to improve the implementation without re-writing your tests
    • Implementations are harder to mock

    You might be able to put in hooks or create mocks that verify that the base method was called, but do you really care how the answer was achieved, or do you care that the answer is right?

    If the particular implementation you require has side effects that you can verify, then that is what you should be validating.