Accessing Internal Methods in Unit Tests

In our code we often have the case where we want to test a method or property that shouldn’t be visible outside of the implementing assembly. In our build system our tests reside in separate assemblies (so that they don’t clog the production code) – which means we can’t access any methods or properties that aren’t public (I probably should add that we are using NUnit as our unit testing framework).

So far we used a workaround where we created a dummy class in our test assembly and derive it from the class we want to test. Then we add additional methods that call the protected methods we really want to test. This always seems a little dirty, and sometimes it isn’t possible at all.

This morning I came around the real solution: there is a little-known attribute InternalsVisibleTo that works like the friend class concept in C++ and makes internal methods and properties visible to another assembly. You specify the attribute in the AssemblyInfo.cs file and give it the name of the assembly that needs to access internal methods.

Example:

Assembly A.dll:

File AssemblyInfo.cs:

...[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ATests")]...

File ClassA.cs:

public class ClassA
{
    internal bool DoSomething()
    {
        return true;
    }
}

Assembly ATests.dll:

File ClassATests.cs:

using NUnit.Framework;
[TestFixture]
public class ClassATests
{
    [Test]
    public void TestSomething()
    {
        ClassA a = new ClassA();
        Assert.IsTrue(a.DoSomething());
    }
}
Advertisements

6 thoughts on “Accessing Internal Methods in Unit Tests

  1. Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  2. Hi,

    thanks for the hint. I always wondered, why are tests so complicated. Now the only thing left to keep me wondering is “Why is the attribute so little-known?”.

  3. Is there a similar way to access Private methods in a UT (nunit) class?
    I know that the VS Test allows something called a PrivateObject but have no idea is there is something similar in NUnit.

    1. I don’t think there’s something out of the box. However, you could use reflection to access private methods.

      1. What I ended up recommending was to create an Internal wrapper method for the Private method, with same signature except, of course, for the scope. Also prefix the method name with UT (for unit test).

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