Skip navigation

Though we cannot test a private method using NUnit, we can do this using Reflection. Suppose, we have a class named “CellPhone” and it has a private method with the following signature —

private bool SendMessage(string MsgBody, int length)

We can test the method using the the following code segment —

Type cellPhoneType = type0f(CellPhone);

MethodInfo sendMessageInfo = cellPhoneType.GetMethod(“SendMessage”, BindingFlags.NonPublic | BindingFlags.Instance);

bool isSent = (bool) sendMessageInfo.Invoke(new CellPhone(), new object[]{“Hello there, how are you”,  24});


The first parameter to the Invoke method is an object on which the method will be operated and the second parameter an array of object. This array contains the parameter values of the method.

The MethodInfo class is in System.Reflection package. Please note that if the “SendMessage” Method was a static method then we had to set the BindingFlags.Static instead of BindingFlags.Instance and in Invoke method, we had to pass null instead of an object. For private static method we will have the following code –

Type cellPhoneType = type0f(CellPhone);

MethodInfo sendMessageInfo = cellPhoneType.GetMethod(“SendMessage”, BindingFlags.NonPublic | BindingFlags.Static);

bool isSent = (bool) sendMessageInfo.Invoke(null, new object[]{“Hello there, how are you”,  24});

Advertisements

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

%d bloggers like this: