Thursday, 16 October 2008

.Net Gem - How to Unit Test Internal Methods

I have recently started redoing unit tests for bit of code at work and came across a internal methods and classes that needed to be tested.


This posed a question of: how do I access the internal methods and classes to test them properly from an external assembly?

I found this little gem that a lot of the developers where I work had not heard of, this doesn't mean that its not common knowledge but thought I would share it a little more.

I have put a scenario below of how it might work.

Being a good TDD developer you decide that you want to write your unit tests for an internal method. You create your .Net Class Library structure so you know what your tests need to call to do your asserts. It may looks something like the image below.


So now you want to start writing your tests and notice that your intellisense is not bringing up your internal class. So what do you do next?

Open the AssemblyInfo.cs file that is in your Properties folder. Add the line [assembly:InternalsVisibleTo("Unit.Tests")] somewhere near the top.

Now your Internal Classes and methods are only visible to Unit.Tests assembly.

Your start writing your unit tests and intellisense should be playing Mr. Nice Guy and we should see something like below.




I hope that it has been useful!

1 comment:

Anonymous said...

Great Tip!! This saved me a ton of time. Thanks!!