Wednesday, February 03, 2010

Test Driven Development (TDD) for asynchronous method calls in Flex using FlexUnit4

I have been using TDD in Java projects for some time now but TDD in Flex was a bit of a challenge until Flash Builder 4 Beta came out with in-built support for FlexUnit4.

Elad Elrom's article Test Driven Development using Flash Builder 4 Beta and FlexUnit provides a great overview of how to use TDD for synchronous calls.

In this blog I will attempt to illustrate the use of TDD for service call to Flickr’s search method. The design pattern used by me here is one I learned in Programming Flex 3 by Chafic Kazoun and Joey Lott.

I use a class that makes an HTTP request and it proxies the response, dispatching an event when the response is returned. I call this class AsyncOperation.as. Though you could write unit tests to test this class, we won’t be doing that here.



Business delegate class is Service.as which holds the methods called by Flex application. This is the class we are going to test. Here's how the class looks like before we write any TDD code.



You can write unit tests to test the instantiation of Service.as class but we are going to skip that.

We start with a test that is going to fail or rather not compile



This test won't compile because searchPhoto(text : String) method does not exist in Service.as class. We'll add that method in Service.as shortly. Before that let's look at a couple of things in this unit test. [Test(async)] notifies FlexUnit4 that this is an asynchronous test. Async.asyncHandler() method creates a special class (the AsyncHandler class) that will monitor the test for an asynchronous event. resultHandler() is our handler function where we write our Asserts to make sure we get the desired results.

Add the following method in Service.as



The test will compile this time but our Assert statement will fail. Assert.assertEquals("ok",xml.@stat) in resultHandler() of ServiceTest.as checks to make sure service call returned OK. In our case it did not because we did not pass api_key and search parameter.

Now, let's fix our searchPhoto method to make the unit test pass.


This time the test will pass. Anytime, you make a change to the method, you should run the test and make sure the service call still returns OK.

You can now refactor the method to clean it up by putting api_key in a class variable and handling spaces between search terms etc. Make sure you add meaningful asserts in resultHandler. Add code that would make the assert fail first and then refactor to make assert pass.

It is considered best practice to automate Unit Testing. You can write Ant Tasks or configure Maven to automate unit testing.

0 comments:

Post a Comment