In Parsley, the injection framework is based around the view hierarchy, and Parsley relies on the build in event bubbling in Flash to configure view-components for IOC.
But what if you want to wire up a unit test with Parsley instead? The unit test does not sit in the view hierarchy so you can’t use the configure event or the inject tag I wrote about earlier in the week, because the configure events simply won’t bubble up to the view manager.
Fortunately there is an easy solution. The Parsley context contains a dynamic context, designed to wire up view components. This is also the right place to wire up the test cases.
Parsley makes this ever so easy, and to wire up your test case, all you need to do is configure the context and add the testcase to the dynamic context.
public class ContextAwareTestCase extends TestCase
{
public var contextClass : Class
override public function setUp() : void
{
var context : Context = FlexContextBuilder.build(contextClass);
context.createDynamicContext().addObject(this);
}
}
So as you can see, it’s very easy. A few gotcha’s though – The context must be created in the setup method. This is because the lifecycle of a test case is different than a regular object, so if you try and create the context in the constructor, you’ll be in a world of pain.
You also want to create the context in the constructor to make sure that any objects you inject into the testcase are in a clean state – to avoid the old issue of testing singletons, where they change state once you’ve used them once.
This kind of thing can be useful to inject mock objects for remote objects for example, or if like me, you’re too lazy to programmatically define dependencies in your test cases;)