Unit testing a private generic method
I had to create another useful test helper today which tests private generic methods. I realise test purists would say you should not test private methods but I find it a much quicker way of unit testing especially when you are maintaining existing code which was not developed using a test driven approach.
1: /// <summary>
2: /// Execute Generic Private Static Method 3: /// </summary>
4: /// <typeparam name="TClass">Type of class executing generic static method</typeparam>
5: /// <param name="methodName">Name of method to execute</param>
6: /// <param name="parameters">Parameters to pass in</param>
7: /// <param name="genericArguments">Generic arguments</param>
8: /// <returns>Return value</returns>
9: public static object ExecuteGenericPrivateStaticMethod<TClass>(string methodName, object[] parameters, Type[] genericArguments)
10: { 11: var typeWithGenericStasticMethod = typeof(TClass); 12: 13: // Grabbing the specific static method 14: var methodInfo = typeWithGenericStasticMethod.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic); 15: 16: if (methodInfo == null) 17: { 18: throw new Exception(string.Format( 19: "Cannot find private method named '{0}' on class of type '{1}'", 20: methodName, 21: typeof(TClass).Name)); 22: } 23: 24: // Binding the method info to generic arguments 25: var genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments); 26: 27: return genericMethodInfo.Invoke(null, parameters); 28: }