12.12. Dynamically Invoking Members

Problem

You have a list of method names that you wish to invoke dynamically within your application. As your code executes, it will pull names off of this list and attempt to invoke these methods. This technique would be useful to create a test harness for components that read in the methods to execute from an XML file and execute them with the given parameters.

Solution

The TestDynamicInvocation method opens the XML configuration file, reads out the test information, and executes each test method dynamically:

public static void TestDynamicInvocation( )
{
    // read in the methods to run from the xml file
    XmlDocument doc = new XmlDocument( );
    doc.Load(@"C:\C#Cookbook\SampleClassLibraryTests.xml");

    // get the tests to run
    XmlNodeList nodes = doc.SelectNodes(@"Tests/Test");

    // run each test method
    foreach(XmlNode node in nodes)
    {
        object obj = DynamicInvoke(node,
                                   @"C:\C#Cookbook\SampleClassLibrary.dll");

        // print out the return
        Console.WriteLine("\tReturned object: " + obj);
        Console.WriteLine("\tReturned object: " + obj.GetType( ).FullName);
    }
}

The XML document in which the test method information is contained looks like this:

<?xml version="1.0" encoding="utf-8" ?> <Tests> <Test className='SampleClassLibrary.SampleClass' methodName='TestMethod1'> <Parameter>Running TestMethod1</Parameter> </Test> <Test className='SampleClassLibrary.SampleClass' methodName='TestMethod2'> <Parameter>Running TestMethod2</Parameter> <Parameter>27</Parameter> </Test> </Tests> ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.