Wednesday, September 16, 2009

A Small Unit Testing Gem

Since I started writing unit tests for my code, I had this question in mind. Let's say I have a project that is a class library. I have a class in that library and this class has some internal methods. Like this:

public class MyClass
{
public void MyPublicMethod
{
int k
// do something ...
int z = MyInternalMethod(k);
// do something else ...
}

internal int MyInternalMethod(int i)
{
// do something ...
}
}

Now I want to write unit tests for these methods. I would create a "UnitTests" project, reference the nunit.framework from it and write something like this:

[TestFixture]
public class UnitTests
{
private MyClass myClass;

[SetUp]
public void SetupTest
{
myClass = new MyClass();
}

[Test]
public void TestMyInternalMethod
{
int z = 100;
int k = myClass.MyInternalMethod(z); //CAN NOT DO THIS!
Assert.AreEqual(k, 100000);
}

[TearDown]
public void TearDown
{
myClass = null;
}
}

Of course, I can not do this, because of the MyInternalMethod scope. Today the StackOverflow guys pointed me to this little gem which is very helpful.

.Net Gem - How to Unit Test Internal Methods

Here's the short summary:

Go to the project that contains MyClass. Locate the AssemblyInfo.cs file. Add the following line to it:

[assembly: InternalsVisibleTo("UnitTests")]

Done!

by . Also posted on my website

No comments: