Sunday, March 2, 2008
Monday, January 14, 2008
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 public||Breaks API|
|private -> internal||Keeps API, but tests must be in the same assmebly|
|private -> internal, InternalsVisibleToAttribute||Keeps API and tests may be in separated assembly|
The last way is the right one.
internalmodifier 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
InternalsVisibleToAttributecomes in handy.
InternalsVisibleToAttributeis 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: