Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test private variables in NUNit?

I have a a static class which has a private variable.

private static Dictionary<strng, string> items = new Dictionary<string, string>();

Many public methods of the class access this dictionary object. Now I want to write NUNit test class (in different library). How can I test this private variable?

like image 719
Learner Avatar asked Dec 20 '10 09:12

Learner


1 Answers

I wouldn't get into the discussion of weather you should or not test internal methods of an internal class. You can expose your internal methods/properties/classes/etc. to an external library, by using the InternalsVisibleToAttribute attribute.

For example, if your unit testing library is named MyUnitTestsLibrary, just add the following in the AssemblyInfo.cs file of your project (the one being tested).

[assembly:InternalsVisibleTo("MyUnitTestsLibrary")]

This will make the MyUnitTestsLibrary library a friend library of your project to be tested and exposing all of it's internal stuff so you can do unit tests.

like image 64
Miljenko Barbir Avatar answered Nov 08 '22 06:11

Miljenko Barbir