Monday, June 23, 2008

Flex: Anonymous Classes as Test Stubs

In my previous post, The State of Flex Testing, I stated that I use anonymous objects as stubs. This entry will show how to easily create stubs that stub methods and properties.

If you simply need a stub that has a property, the following code is all you'll need.

{state: "ready"}

The above code creates an object that response with "ready" to the message state. Adding methods is also easy if you remember that you can create properties that store anonymous functions (just like Javascript). If you need the execute method to return true, the following stub should do the trick.

{state: "ready", execute: function(){ return true }}

That's really it. You can define methods and properties on anonymous objects as you please.

Is it beautiful? Not really. I've considered a few other options would allow you to define methods without the anonymous function, but it's never been so annoying that it was worth spending the time to get the implementation correct. I suspect anyone who put their mind to it could come up with a nice implementation in a short amount of time.
Post a Comment