Unknown classes, and classes to XML
In working on preparing some stuff for a training I am doing on Unit Testing in Flex, I wanted to find a way that I could reference any class, and any method in that class without ever knowning the actual class name or method names. This is a pretty slick solution that will go through and add all of my test case methods to my FlexUnit testing suite.
1) I needed to call the class, but do it without ever knowing its name. The way to do this is using getQualifiedClassName to get a string of the class. Fully qualified means that it is the full path, so something like "com.chasebrammer.samples.TestClass"
2) I needed to call the class based off of its qualifiedName. To do this, I used a little used native method called getDefinitionByName
3) After getting what class I am calling from, I wanted to get all of the method names in that class, and find any that have the name "test" on the front, and add them to my testSuite. To get the xml of an object (or class), it is actually really simple, here is an example. Then it was just a matter of looping the code to find the right methods and add them to the test suite. So, below is the code, I find code talks better than description of code.
private function createSuite():TestSuite { var ts:TestSuite = new TestSuite(); var className:String = getQualifiedClassName(this); addTests(ts, getDefinitionByName(className) as Class); return ts; } private function addTests(suite:TestSuite, testerClass:Class):void { var desc:XML = describeType(new testerClass("method")); for each(var method:XML in desc.method) { if (method.@name.substr(0, 4) == "test") suite.addTest(new testerClass(method.@name)); } }