views:

172

answers:

3

I am trying to develop an NUnit addin that dynamically adds test methods to a suite from an object that contains a list of Action delegates. The problem is that NUnit appears to be leaning heavily on reflection to get the job done. Consequently, it looks like there's no simple way to add my Actions directly to the suite.

I must, instead, add MethodInfo objects. This would normally work, but the Action delegates are anonymous, so I would have to build the types and methods to accomplish this. I need to find an easier way to do this, without resorting to using Emit. Does anyone know how to easily create MethodInfo instances from Action delegates?

A: 
MethodInvoker CvtActionToMI(Action d)
{
   MethodInvoker converted = delegate { d(); };
   return converted;
}

Sorry, not what you wanted.

Note that all delegates are multicast, so there isn't guaranteed to be a unique MethodInfo. This will get you all of them:

MethodInfo[] CvtActionToMIArray(Action d)
{
   if (d == null) return new MethodInfo[0];
   Delegate[] targets = d.GetInvocationList();
   MethodInfo[] converted = new MethodInfo[targets.Length];
   for( int i = 0; i < targets.Length; ++i ) converted[i] = targets[i].Method;
   return converted;
}

You're losing the information about the target objects though (uncurrying the delegate), so I don't expect NUnit to be able to successfully call anything afterwards.

Ben Voigt
This will produce a compile-time error...
Aaronaught
sorry, I was thinking of MethodInvoker when I saw MethodInfo.
Ben Voigt
+1 (to get you back to zero). As it turns out, d.Method was all I needed. It does work in NUnit, although the naming is funky. I'll have to create my own test class to fix that.
Michael Meadows
+2  A: 

You don't need to "create" a MethodInfo, you can just retrieve it from the delegate :

Action action = () => Console.WriteLine("Hello world !");
MethodInfo method = action.Method
Thomas Levesque
+1, You and Fede both had the correct answer. I accepted his, because tie goes to the guy with two less digits on his rep. :)
Michael Meadows
+1  A: 

Have you tried Action's Method property? I mean something like:

MethodInfo GetMI(Action a)
{
    return a.Method;
}
Fede
No I haven't tried that, but it's exactly what I needed. Thanks.
Michael Meadows