Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Test Private Methods with NUnit
October 4, 2010

There is a debate in the Test Driven Development (TDD) community about whether or not it's appropriate to test private methods with unit test tools like NUnit. By default NUnit will not allow you to test private methods. But you can test private methods using .NET's Reflection API.

Take a look at the code fragment below. To call a class' private method, instantiate a Type object for the class. Then call the Type object's GetMethod method, specifying BindingFlags.Private. You'll also need to specify BindingFlags.Static if the method is static. Once you've called GetMethod, you'll have a MethodInfo object for the method. Finally, call the MethodInfo object's Invoke method to call the private method. Invoke's first argument is the object on which the method is being called. Since the code below is calling a static method, the first argument is null. The second argument is an object array containing all the arguments to the method.

In the code below the second argument to the private GridIsValid method is an enum which is also private. The GetNestedType method retrieves this enum, and Enum.GetValues is used to retrieve the enum's values.

...

Type puzzleType = typeof(Puzzle);

// Prepare to call GridIsValid private method.
MethodInfo gridIsValidMethodInfo = puzzleType.GetMethod("GridIsValid", BindingFlags.NonPublic | BindingFlags.Static);

Type gridType = puzzleType.GetNestedType("GridType", BindingFlags.NonPublic | BindingFlags.Static);

Array gridTypeValues = Enum.GetValues(gridType);

// Make sure that the test grid is valid.
bool bResult = (bool) gridIsValidMethodInfo.Invoke(null, new object[] { puzzleGrid, gridTypeValues.GetValue(0) });

Assert.AreEqual(true, bResult);

// Now determine the number of solutions (should be > 1).

// Prepare to call EnumerateSolutions private method.
MethodInfo enumerateSolutionsMethodInfo = puzzleType.GetMethod("EnumerateSolutions", BindingFlags.NonPublic | BindingFlags.Static);

Hashtable solutions = new Hashtable();
enumerateSolutionsMethodInfo.Invoke(null, new object[] { puzzleGrid, 0, 0, solutions });

...
Keywords: NUnit, Test-Driven Development, TDD, Reflection, Private Methods

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015