Reputation: 14426
I have written an application that unit tests our hardware via a internet browser.
I have command classes in the assembly that are a wrapper around individual web browser actions such as ticking a checkbox, selecting from a dropdown box as such:
BasicConfigurationCommands
EventConfigurationCommands
StabilizationCommands
and a set of test classes, that use the command classes to perform scripted tests:
ConfigurationTests
StabilizationTests
These are then invoked via the GUI to run prescripted tests by our QA team. However, as the firmware is changed quite quickly between the releases it would be great if a developer could write an XML file that could invoke either the tests or the commands:
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite>
<StabilizationTests>
<StressTest repetition="10" />
</StabilizationTests>
<BasicConfigurationCommands>
<SelectConfig number="2" />
<ChangeConfigProperties name="Weeeeee" timeOut="15000" delay="1000"/>
<ApplyConfig />
</BasicConfigurationCommands>
</testsuite>
I have been looking at the System.Reflection
class and have seen examples using GetMethod
and then Invoke
. This requires me to create the class object at compile time and I would like to do all of this at runtime.
I would need to scan the whole assembly for the class name and then scan for the method within the class.
This seems a large solution, so any information pointing me (and future readers of this post) towards an answer would be great!
Thanks for reading,
Matt
Upvotes: 0
Views: 679
Reputation: 55966
To Find all classes in an assembly:
public Type FindClass(string name)
{
Assembly ass = null;
ass = Assembly.Load("System.My.Assembly"); // Load from the GAC
ass = Assembly.LoadFile(@"c:\System.My.Assembly.dll"); // Load from file
ass = Assembly.LoadFrom("System.My.Assembly"); // Load from GAC or File
foreach(Type t in ass.GetTypes())
{
if (t.Name == name)
return t;
}
return null;
}
In reality you should tag your class with an attribute, it makes them more discoverable.
To instantiate an instance of said class:
public T Instantiate<T>(Type typ, object[] arguments)
{
return (T)Activator.CreateInstance(typ, arguments, null);
}
Don't forget, you should probably wrap these with appropriate try/catch blocks
Then to find a method on a class
Type t = FindClass("MyType");
MethodInfo meth = t.GetMethod("TestSomething", typeof(string), typeof(int)); // finds public ??? TestSomething(string, int)
Just play around with the Object Browser in VStudio and learn the Reflection classes, there's lots you can do.
Upvotes: 2