Wednesday, October 05, 2005

Test an internal class in .Net?

I recently ran into this problem. Like most of you we have separate projects for our unit tests. And off course we also have a helper to test private functions using reflection.
But how do you test an internal class?
The helper we have won't suffice. Because it needs an instance of the called class. So how do we do this? Again using reflection? Hmmm..
Well the solution is surprisingly easy.
We will link the internal class to our Test project.
To do this go to Add Existing Item -> Select File you wish to Link.
Now instead of clicking on the Open button, which will make a copy of the file in your project and we don't want that, click on the Drop Down and select Link file.
This will link the selected file to your test project, this way you can use the internal class, but the file is not actually copied to your Test project. And thus, code changes will automatically be used.
Easy, isn't it?

4 Comments:

At 17:32, Anonymous Nemesis Blue said...

Nice solution! Helps me a lot (even though we are two years on from the original post). Thanks.

 
At 23:01, Blogger epox from russia said...

Yes, it could be nice in case you have strongly named assembly and don't want to spend a minute to generate a public key for your test assembly.

Also, ladies and gentlemen, please read C# Programming Guide (http://msdn2.microsoft.com/en-us/library/0tke9fxk.aspx) . It's not so long as you could think.

In two words all you need is to add:
[assembly:InternalsVisibleTo("MyTestDllName")]
line to your AssemblyInfo.cs file.

Thank you.

 
At 15:07, Blogger Florian Doyon said...

Epox, thanks. The InternalsVisibleToAttribute section completely slipped my mind.

Cheers,

 
At 02:27, Anonymous Clayton said...

You mention that you are unit testing private methods using reflection. IMO this is very bad practice. Unit testing should focus on public interfaces. By testing private members, you are coupling your tests to private implementation details, which makes them fragile, and hinders refactoring which is a critical part of TDD.

 

Post a Comment

<< Home