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
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021