Vadim's Weblog

Never stop learning.

MbUnit: Testing Internal classes

Posted by Vadim on September 5, 2007

Jonathan ‘Peli’ de Halleux wrote an article ‘Pex It: Testing Internal classes‘.   I just want to let the world know that you also can test non-public classes with MbUnit.  You need  version or higher to use this feature.

In example bellow we test IsWhite(Char) method of System.Number class inside mscorlib assembly.  Using Reflector you can see that Number is an internal class and IsWhite is a private method of this class.  We can test this method event if we don’t have the source code.

private static readonly string MSCorLibAssembly = 
    + @"\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll";
public void InternalClassTest()
    string className = "System.Number";
    object obj = 
        Reflector.CreateInstance(MSCorLibAssembly, className);
            AccessModifier.Default, obj, "IsWhite", ' '));
            AccessModifier.Default, obj, "IsWhite", 'V'));

The Number class has only default constructor.  It means we don’t need to send parameters when creating an instance.

Let’s look at another example.  This time we’re going to write test for the Key and Value properties of System.Collections.KeyValuePairs class.  This class is also internal.  If you don’t believe me, use Reflector.  KeyValuePairs class has only one constructor that takes two Object parameters.

public void InternalClassNonDefaultConstructor()
    string className = "System.Collections.KeyValuePairs";
    object obj = 
        Reflector.CreateInstance(MSCorLibAssembly, className, 1, 'A');
    Assert.AreEqual(1, Reflector.GetProperty(obj, "Key"));
    Assert.AreEqual('A', Reflector.GetProperty(obj, "Value"));

 Happy Testing :)


3 Responses to “MbUnit: Testing Internal classes”

  1. JK said

    I must be blind…but where/in what namespace is this Reflector class that you reference (Reflector.CreateInstance(…)) in your first code example?

  2. vkreynin said

    You need to add reference to MbUnit.Framework.2.0 (additional to MbUnit.Framework). After that add using statement like one bellow.

    using MbUnit.Framework.Reflection;

    Hope it helps.

  3. WOW just what I was looking for. Came here by searching for
    data recovery expert

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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

%d bloggers like this: