Unit testing a generic private static method on a base class
I created this useful testing method I need to create today, uses recursion to loop down through to the correct base class to execute:
1: /// <summary>
2: /// Execute private static method on a base of the passed sub class type3: /// </summary>
4: /// <typeparam name="TSubClass">Type of sub class</typeparam>
5: /// <param name="baseName">Base name to execute method on</param>
6: /// <param name="methodName">Method name to execute</param>
7: /// <param name="parameters">Parameters to use</param>
8: /// <returns>Return from invocation</returns>
9: public static object ExecutePrivateStaticMethodOnBase<TSubClass>(string baseName, string methodName, object[] parameters)
10: { 11: // Walk up the type rope 12: var baseType = CheckBaseType(typeof(TSubClass), baseName, typeof(TSubClass).Name); 13: 14: var mi = baseType.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)15: .Where(m => m.Name == methodName).FirstOrDefault();
16: 17: if (mi == null) 18: { 19: throw new Exception(string.Format( 20: "Cannot find private method '{0}' on a base named '{1}' of class of type '{2}'", 21: methodName, 22: baseName, 23: typeof(TSubClass).Name)); 24: } 25: 26: return mi.Invoke(null, parameters); 27: }The recursive method is as follows:
1: /// <summary>
2: /// Check base type3: /// </summary>
4: /// <param name="subClassType">Sub class type to check</param>
5: /// <param name="baseName">Base name of type</param>
6: /// <param name="originalEntry">Original entry type</param>
7: /// <returns>The actual type if we find it</returns>
8: private static Type CheckBaseType(Type subClassType, string baseName, string originalEntry) 9: { 10: var baseType = subClassType.BaseType; 11: if (baseType != null && baseType.Name == baseName) 12: { 13: return baseType; 14: } 15: 16: if (baseType != null) 17: { 18: return CheckBaseType(baseType, baseName, originalEntry); 19: } 20: 21: // Not found 22: throw new InvalidOperationException(string.Format("Cannot find {0} as a base type of {1}.", baseName, originalEntry)); 23: }As you can see this just walks up the class tree to find the class that matches.