Wednesday, 23 December 2009

Catching the real Exception from a method invoke (through reflection)

Sometimes when invoking a method by reflection the method being invoked might throw an exception, but the reflection framework obscures this by wrapping the thrown exception as

   TargetInvocationException 

This is especially annoying if you have unit tests to excersise private methods of an assembly invoked from the test by reflection, you may be wanting to test a specific exception, here's a useful wrapper function to help out here:

        public void ExpectedExceptionMethodInvokeWrapper(object[] invokeParams, object instance, MethodInfo methodToInvoke)
        {
            try
            {
                methodToInvoke.Invoke(instance, invokeParams);

                // Fail: Expected Exception of T
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException is T)
                {
                    throw tie.InnerException;
                }
                else
                {
                    // Fail: Expected Exception of T
                }
            }
            catch
            {
                // Fail: Expected TargetInvocationException, with valid inner exception
            }
        }

No comments: