Testing Internal Methods

Over on the Windojitsu blog, Shawn has come up with a minimalist alternative to NUnit. The main reason given is not wanting to inflict a dependency on anyone who wants to build his project.

TestDriven.NET already supports the idea of light weight testing frameworks. These frameworks can be invisible to the outside world (non-public) and conditionaly compiled out. They can be used if you want to test internal classes/methods or if you don't want a dependency on the 'nunit.framework' assembly.

Here is an example framework, quite similar to the one Shawn defined.

#if TEST
namespace Testing.Framework
{
using System;

[AttributeUsage(AttributeTargets.Class)]
internal class TestFixtureAttribute : Attribute { }

[AttributeUsage(AttributeTargets.Method)]
internal class TestAttribute : Attribute { }
}
#endif

You can then write your unit tests as follows (note that classes and methods are internal and private by default).

#if TEST
namespace Testing.Framework
{
using
System;
using Testing.Framework;
 [TestFixture]
class TestFix
{
[Test] void TestUnit()
{
throw new Exception("Boom!");
}
}
}
#endif

Remember to define a TEST conditional compilation constant in your Debug builds!

Update: Gus pointed out that "Unused referenced assemblies don't actually stick around". If you are disciplined enough to wrap all of your tests in #if TEST blocks - any referenced 'nunit.framework' assembly won't be referenced in the final output. If you use the above method and conditionaly compile out the framework itself, any tests that reference it won't compile if TEST isn't defined (you don't have to count on discipline).

I'm not saying that light weight testing frameworks are a good thing (otherwize I would have blogged about them before). They are however a thing and if you need them (or are paranoid) they're supported. ;o)

4 Comments

  • We use Kevin's method. It works well but when it goes wrong the missing #if TEST conditions are a complete nightmare to find. :(

    All our tests are in files that should be entirely surrounded by a "#if TEST", so my current method is to switch to a configuration without TEST defined and do a find if files for "using MbUnit". Then it's a matter of patiently tapping F8 looking out for code that isn't grey...

    Maybe by editing the VS2005 projects the references themselves can be made conditional, now it's all MSBuild under the covers.

  • I also use this method : Create a separate 'test project' in the same solution.

    This project is than saved under

    <realproject>\test<realproject>



    This keeps the tests close to the project beiing tested. So no more dozens of testx somewhere undere a certain folder of which you do no longer know what they're testing.



  • When keeping unit tests in a separate project, how can we test the internal classes of an assembly?





  • 357850.. Great! :)

Comments have been disabled for this content.