Tuesday, September 3, 2013

How to expose internal methods to a different assembly

Let's say you create this method - let's call it MethodX. Now MethodX is only used within the project - so you marked it as "internal". So now you want to test this MethodX.

Now, I know that in theory MethodX is used internally in the project, which exposing public members of public classes etc - and those public classes and their members are the ones ought to be tested. Using MethodX or not is an implementation detail that the consumer does not need to know, hence does not need to be tested specifically. Yupe, agreed - that is all good.

Now, let's set that aside for a moment - and if you want to test the internal MethodX directly, how would you do it? Of course, the easiest solution is by making MethodX (and the class containing it) to be public. But, then you must remember to convert it back (and forth) every time you run your tests - which is quickly becoming a pain.

It turns out, there is a flag/attribute that you can set in your class declaration to specifically mark a class and its internals to be visible to a different set of assembly. Take a look at this example below:
[assembly:InternalsVisibleTo("MyProject.Tests")]
namespace MyProject
{
    public class MyClass 
    {
        internal void MethodX() 
        {
            // ...
        }
    }
} 
So normally, although the class MyClass is public and is available to public, but the method MethodX is not accessible from outside the same assembly. But, upon putting the InternalsVisibleToAttribute, now MethodX is accessible from MyProject.Tests assembly. If this consuming assembly is your test project, then you can start to build a test for it just like testing against a public method.

No comments: