How do I go about unit testing a private method that gets called in a loop like this one:
// Calls MethodToUnitTest in a loop
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
}
// Called multiple times by Generate
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:
Change the visibility of
MethodToUnitTest
topublic
(and possibly even move it to another class) then write unit test codes that exercise it.Con: The output of
MethodToUnitTest
is only forGenerate
so there is no need to make it public or move it to another class. Furthermore,MethodToUnitTest
is just a simple function.Test
MethodToUnitTest
by callingGenerate
: Con: Just feels unnatural.
Sample tests
Assert.AreEqual("Divisible by 2", Generate(2));
Assert.AreEqual("Divisible by 3", Generate(3));
Assert.AreEqual("Divisible by 2, Divisible by 3", Generate(2, 3));
// ...etc
Which solution is better? At what point do you break down a method into multiple individually testable methods?