12

How do I test private methods and internal classes using NUnit?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
SNA
  • 7,528
  • 12
  • 44
  • 60

5 Answers5

32

Private methods:

If you're trying to test non-public methods, it usually means you're doing it wrong.

If there's functionality that you want to test, but don't want to make public on your class, the code is trying to tell you something. Your class probably has too many responsibilities. You should seriously consider extracting that private functionality into a new class, writing tests for the new class, and making your old class have a private instance of the new class.

Internal classes:

This one is more valid, especially if you're writing a class library for others to reuse. You may have classes that aren't designed for general use, but that you want to write unit tests for.

For this case, take a look at InternalsVisibleToAttribute.

Joe White
  • 94,807
  • 60
  • 220
  • 330
  • 3
    It's also worth noting that InternalsVisibleTo can be used to expose constructors/methods only used by the test assembly and keep those hidden from client code. – Jeff LaFay May 03 '11 at 19:23
5

I typically don't. If you thoroughly test the public methods that use private methods and internal classes then you should be able to test the full range of the private functionality without exposing it.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
2

The way I handle this is that I make all my methods public. I know that sounds bad, but bear with me a moment.

When using IoC you have an interface for every class that has some logic in it. So basically you code against the interface, and not the actual implementation. What this let's you do is to mark all of the methods public and it does't affect the way that the class is used, except it makes it possible to write unit tests for every method in that class.

Bart
  • 19,692
  • 7
  • 68
  • 77
TuomasK
  • 1,849
  • 3
  • 13
  • 19
1

Just use the solution shown here: C# "internal" access modifier when doing unit testing

and you will see that internals can and should be tested.

user8276908
  • 1,051
  • 8
  • 20
0

You have to expose a means to invoke them, possibly through a test-specific derived class.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117