/// <summary> /// Dynamically Invokes either a constructor, instance or static method as supplied with the /// provided arguments an instance as appropriate. /// </summary> /// <param name = "method">The method to invoke.</param> /// <param name = "parameters">The parameters to use.</param> /// <param name = "instance">The instance to invoke the method against if it is an instance method.</param> /// <returns>The results of the instance invocation.</returns> private static object InternalDynaInvoke(MethodBase method, object[] parameters, object instance = null) { try { if (typeof(ConstructorInfo).IsAssignableFrom(method.GetType())) { return(method.As <ConstructorInfo>().Invoke(parameters)); } if (instance.IsNotNull() && method.IsStatic) { return(method.Invoke(null, TestHelp.Array(instance).Union(parameters).ToArray())); } else { return(method.Invoke(instance, parameters)); } } catch (TargetInvocationException ex) { // An exception occurring inside of the Target when Invoked via // reflection will get caught and rethrown as a TargetInvocationException // In these cases we want to have the inner exception sent up the // stack so that the actual exception is presented to the test case. // This code removes the TargetInvocationException and "fixes" the // call stack to match. // Use reflections to get the inner field that holds the stack inside // of an exception. FieldInfo remoteStackTrace = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); // Set the InnerException._remoteStackTraceString // to the current InnerException.StackTrace // This "fixes" the stack trace so that it does not appear to originate // from here when we re-throw the inner exception. remoteStackTrace.SetValue(ex.InnerException, ex.InnerException.StackTrace + Environment.NewLine); // Re-throw the inner exception. throw ex.InnerException; } }