Skip navigation

Category Archives: NUnit test

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