Home > Software engineering >  How do I write a unit test on a method that calls another private method in that class?
How do I write a unit test on a method that calls another private method in that class?

Time:03-10

I have a class that generates some tokens. I have some external dependencies and unit tested those dependencies by mocking and verified the number of times the method was called. However, After calling those external dependencies, I have a private method called to get the token. Ex:

var res = GetToken(arg1, arg2, arg3);

Do I have to unit test on that statement and if so how?

CodePudding user response:

You generally don't need to unit test private methods. You unit test the public methods that use those private methods, mocking any external dependencies. You verify that the outputs of public methods are correct, which assumes that the results of the private methods that they call are also correct. That gives you the freedom to change the private implementation without braking your unit tests (so long as the public interface is unaffected).

There may be cases where you want explicitly unit test a private method in isolation, but it is the exception, not the rule.

CodePudding user response:

Every private method is called by a public method in the end. Maybe not directly, but somewhere in the callstack there is a public method. You test this public method, and because it calls the private method, you indirectly test it. An example:

public class Test
{
   public int Result {get;private set;}

   public PerformAction(int a, int b)
   {
       int value = a   b;
       SetResult(value);
   }
   
   private void SetResult(int value)
   {
      Result = value;
   }
}

If you test PerformAction, you call it with e.g. 4 and 5, and then you check whether the Result property has the value 9. By that, you tested also the private SetResult method indirectly. If it had a bug, your test would fail.

Don't try to test private method directly. In theory, it would be possible via reflection, but it leads to very brittle tests which have to change quite often. In general, you should test observable behaviour (which is commonly public), no implementation details (which are commonly private).

  • Related