Unit Testing and Cyclomatic Complexity

by UnitTestingN00b   Last Updated October 25, 2017 10:05 AM

How do I go about unit testing a private method that gets called in a loop like this one:

    public static string Generate(params int[] values)
    {
        if (values.Any(i => i == 0)) // return empty string if any value contains 0 
            return "";

        return string.Join(", ", values.Select(MethodToUnitTest)); // return a comma delimited string
    }

    private static string MethodToUnitTest(int value)
    {
        if (value % 2 == 0)
            return "Divisible by 2";

        if (value % 3 == 0)
            return "Divisible by 3";

        return value.ToString();
    }

I can see two options:

  1. Change the visibility of MethodToUnitTest to public (and possibly even move it to another class) then write unit test codes that exercise it.

    Con: The output of MethodToUnitTest is only for Generate so there is no need to make it public or move it to another class. Furthermore, MethodToUnitTest is just a simple function.

  2. Test MethodToUnitTest by calling Generate: Con: Just feels unnatural.

Sample tests

Assert.AreEqual("Divisible by 2", Generate(2));

Assert.AreEqual("Divisible by 3", Generate(3));

// ...etc

Which solution is better? At what point do you break down a method into multiple individually testable methods?



Answers 1


How do I go about unit testing a private method

You don't!

Unittests verify public observable behavior (where "public" does not imply public visibility of the tested interface...) which is the return values and the communication with dependencies.


I can see two options:

Another option is to move that method into a separate class that becomes a dependency of your code under test and could be replaces with a mock on which you can verify the calls of this method.


At what point do you break down a method into multiple individually testable methods?

This boils down to the question What is a unit? I like the answer of Roy Osherove in The Art of Unittesting:

A Unit is all the code that has the same reason to change.

So a private method becomes a "unit" when it appears to have its own "context" which somehow differs from the context if the other methods.

Another reason to make it a separate unit is that it is hard to test.

Timothy Truckle
Timothy Truckle
October 25, 2017 10:02 AM

Related Questions



How should service method parameters be?

Updated November 18, 2017 16:05 PM


How do unit tests facilitate design?

Updated February 10, 2017 14:02 PM