hash_bucket()

Unit testing internal methods

Posted on: January 12, 2009

Here’s a little gem.

Most people like to keep their unit test assemblies and code separate from the code being tested (maintainability is such a nice thing). This however raises the issue of how to write tests for methods and classes that are marked internal.

Lots of different approaches exist, such as editing the *.csproj file by hand to include (inject) the code file containing the tests in to the code being tested. This, however is not a very smooth approach.

Thankfully there is a much easier approach using a technique called Friend Assemblies. Basically it’s a way of saying that Assembly A and Assembly B are friends, meaning that B can peek into A’s little secrets marked Internal.
Here’s how to set this up:

1. Add the Assembly Attribute ‘InternalsVisibleTo’ to the assembly being tested:
This goes into the file ‘AssemblyInfo.cs’, an autogenerated file in the Properties folder of your project.

[assembly: InternalsVisibleTo(“Tests.dll”)]

2. Make sure that the assembly containing the tests reference the assembly being tested, and that the output matches the name you typed in the Assembly Attribute (in this case ‘Tests.dll’).

One good thing to know is that sometimes your assemblies fail to make friends because the output of you test assembly has not been explicitly named. In such cases you should make sure to compile the test assembly using the ‘/out:’ switch.
/out:Tests.dll

As always, MSDN has the full story here:
http://msdn.microsoft.com/en-us/library/0tke9fxk(VS.80).aspx

and here:
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx

Advertisements

2 Responses to "Unit testing internal methods"

Nice one! I’ve got a question though:
Doesn’t adding the InternalsVisibleTo attribute to the assemblyinfo file expose all internal methods from all classes in that assembly?
Maybe it would be better to add it only where you need it?

are you talking about adding it as a class attribute?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

.

This blog has no clear focus. It has a focus though, it's just not very clear at the moment...

Dev Env.

Visual Studio 2008 Prof / NUnit / Gallio / csUnit / STools (ExactMagic) / doxygen / dxCore / TypeMock / TestDriven.net / SequenceViz / CLRProfiler / Snoop / Reflector / Mole / FxCop / Subversion / TortoiseSVN / SlikSVN / CruiseControl.net / msbuild / nant

Blog Stats

  • 81,377 hits