Search code examples
c#unit-testingmicrosoft-fakes

Shim a private method of a component with external dependencies


I'm studying Microsoft Fakes to implement unit tests in a project of mine.

If i've understood correctly, i use stubs to set the behavior of external components (that implement interfaces) that the main component i want to test is dependent from.

I use shibs to simulate the behavior of specific pieces of code at runtime.

My goal is to test a method of a manager class that has dependencies to other components all implementing interfaces. This method, among the other things, calls a private method. In the test method i need to force the result of that private method.

The scenario is similar to the following code:

public class MyManager : IMyManager {

    private IMyDependentManager _myDependentManager;

    public MyManager(IMyDependentManager myDependentManager) {
        this._myDependentManager = myDependentManager;
    }

    public void MyMethodToTest(data1, data2,...) { // method to test
        ...
        byte[] res = MyPrivateMethod(data1); // i want to set the result of this method in order to NOT execute it, otherwise the test will fail
        ...
    }

    private byte[] MyPrivateMethod(data1) {

    }
}

Any suggestion on how to setup the test would be very helpful.


Solution

  • The implication from the question and the private method's signature is that you need to separate the concerns.

    Consider what the responsibility of your manager class is. Now consider what that private method is doing. I suspect you will find that the private method is not something that the manager class is (directly) responsible for - it is doing something that the manager should be delegating.

    Move that private method into a separate class (as a public method), and use dependency injection to give it to the manager class, I would suggest doing this via an interface.

    Now when testing your manager, you can supply it's constructor with a mock of the new class's interface to return whatever you like.