Monday, January 14, 2008

How to Test Private Fields and Methods using NUnit

When you write unit tests, you need call some methods and compare their results with expected values as well as check overall state of objects through fields and properties. It is good to separate tests from testing code. But, what about testing private fields and methods? In addition, tests may be in a standalone assembly. Have a look at the possible ways:











everything is publicBreaks API
private -> internalKeeps API, but tests must be in the same assmebly
private -> internal, InternalsVisibleToAttributeKeeps API and tests may be in separated assembly


The last way is the right one. internal modifier is clear. Be careful about protected fields, their modifier should be protected internal. All members are visible within the scope of assembly, but tests are in a separated assembly. What now? The InternalsVisibleToAttribute comes in handy.

InternalsVisibleToAttribute is supported in .NET framework 2.0 and higher. This attribute specifies the "friend assembly" - assembly, that has access to all internal members. So, the last one step is to add the following line to AssemblyInfo.cs file:

[assembly: InternalsVisibleTo("FriendAssemblyName, PublicKey=...")]



kick it on DotNetKicks.com

No comments: