As a developer, it’s hard to stick to writing unit tests. It’s really awesome if you do test driven development and write them first, but a lot of the times I find it hard to sick to this plan for various reasons. No, it’s not cause I don’t want to….sort of.
One of the really cool things about the unit test framework built into visual studio, is the ability to create a unit test that will test even your private methods. You can do this by right clicking in the .cs and selecting the “Create Private Accessor” option, which will then offer you the list of test projects to generate this class in. Here is the menu:
You can read more about doing this here. Now, we should be able create an instance of you new accessor in the unit test by instantiating MyObject_Accessor. In the instance of the object, you should now have access to all of the fields and methods of the original object that are not public. Sweet.
Hanging off of this accessor object, you will see a property called Target, of type Object. This holds something called a PrivateObject, which should be a wrapper around your original object, MyObject. I have been doing a ton of Dependency Injection in my projects lately using Unity to decouple my projects from eachother. Using the PrivateObject is critical to creating a mock version of my dependency injector for the purposes of unit testing.
In a follow up to this, I will post some code showing how to create a mock injector, and how to make use of the PrivateObject in that injector. Now go test!