When I first started using unit tests I encountered two problems. First was being able to test private methods and fields and second falling behind on keeping unit tests up to date when rapid development was taking place. Consequently I adopted the approach below for my unit tests.
#if UNITTEST
using NUnit.Framework;
#endif
public class MyBlackMagic
{
private int DoMagic()
{
return 1;
}
#if UNITTEST
[TestFixture]
public class MyBlackMagicUnitTest
{
[TestFixtureSetUp]
public void Init()
{
log4net.Config.BasicConfigurator.Configure();
}
[Test]
public void DoMagicTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(DoMagic() == 1, "You are not a real magician!");
}
}
#endif
}
I find that approach overcomes my two problems and it's a flick of a pre-compiler switch to make sure all the unit tests compile.
My problem now is that I am moving to a new project where the talk is of using seperate assemblies to hold the unit tests. Before I dive in and start expounding on the virtues of the internal class approach as shown above I'd like to know if anyone thinks it has any shortcomings?
Edit:
Just to add a couple of points around some of the mentioned weaknesses:
- The unit testing code will never impact the production code since the UNITTEST pre-compiler flag gets switched off,
- The unit test code doesn't make the main code any less readable since it's placed at the bottom of each class and wrapped in a Visual Studio region directive,
- I find the internal unit test class means the main class is actually simpler as there are no extra methods or properties that have to be exposed just for testing. There will always be cases where you want to test some internal state of a class as part of a unit test sooner or later...