Test Driven Development (TDD) Preso 360|Flex 2010


Published on

Test Driven Development (TDD) Preso 360|Flex 2010

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Test Driven Development (TDD) Preso 360|Flex 2010

  1. 1. Test Driven Development (TDD)<br />San Jose 360|Flex<br />@EladElrom<br />
  2. 2. @EladElrom<br />Associate Dev Director @ Sigma Group<br />Senior Flash Engineer & Lead<br />Technical Writer<br />FlashAndTheCity Organizer<br />Adobe Community Professional<br />
  3. 3. TOC<br />USING FLEXUNIT 4 WITH TEST DRIVEN DEVELOPMENT<br />Test Driven Development quick overview<br />Defining Application’s Objective<br />User Stories<br />GETTING STARTED <br />Creating the application<br />Creating the class to be tested<br />Creating your first Test Suite<br />Add your first test case class<br />IMPLEMENTING YOUR USER STORIES<br />Retrieve Tweets User Story<br />Retrieve tweets every few seconds User Story<br />
  4. 4. Show & tell<br />How many of you have used TDD?<br />How have of you have tried to use TDD and gave up?<br />How many always wanted wanted to use TDD but never did?<br />
  5. 5. In Software Engineer, What’s your development techniques options? <br />
  6. 6. Asshole Driven Development (ADD)<br />Any team where the biggest jerk makes all the big decisions is asshole driven development. All wisdom, logic or process goes out the window when Mr. Asshole is in the room, doing whatever idiotic, selfish thing he thinks is best. There may rules and processes, but Mr. A breaks them and people follow anyway. <br />Scott Berkun<br />
  7. 7. Cover Your Ass Engineering (CYAE)<br />The driving force behind most individual efforts is to make sure than when the shit hits the fan, they are not to blame.<br />Scott Berkun<br />
  8. 8. Duct-tape Driven Design (DDD)<br />Get it out the door as quickly as possible, cut-n-paste from anything that you find that works on Google, if it works it’s ready<br />
  9. 9. Now Seriously... <br />
  10. 10.
  11. 11. WaterfallSoftware Development Process<br />
  12. 12. Disadvantages of Waterfall Process<br />Creating tasks based on developer’s opinion rather than project’s needs.<br />Spending time on technical design documents such as UML diagrams.<br />May create code that is not used in the app and increase development time.<br />One programmer code may break another programmer code.<br />Many time methods do more than one task and code is hard to maintain.<br />Changing requirements may require re-engineering parts of the app.<br />
  13. 13. What’s the alternative?<br />
  14. 14. What’s TDD? <br />The concept is pretty simple. You write your tests before you write your code. It’s that simple and worth repeating: write tests before code!<br />Test Driven Development is a software development technique in which programmers are writing a failed test that will define the functionality before writing the actual code.<br />
  15. 15. Process overview<br />
  16. 16. Developers are lazy!<br />Software developers our job is to be lazy.Lazy = Efficient.. Really?<br />We automate repetitive tasks. Yet we most of our time testing and debugging our code manually (80% as some studies suggest).<br />Why would you choose to do this repetitive and annoying task when you automate all of the others?<br />
  17. 17. Automate testing<br />Let humans do the work they do best while letting computers do the work they do best and ending up with code that is more stable and more maintainable!<br />
  18. 18. Furthermore<br />The concept of TDD is based on Extreme Programming (XP) development paradigm, which talks about teams that work on the development of dynamic projects with changing requirements and a development cycle that includes TDD for writing the test before the code itself. TDD is not the complete development cycle; it is only part of the Extreme Programming (XP) development paradigm. Preparing the tests before writing the code helps a development team to demonstrate their work in small steps, rather than making the customer or other stakeholders wait for the complete result.<br />Moving in small increments also makes it easier to accommodate changing requirements and helps ensure that your code does what it needs to do, and nothing more. It is important to mention that the focus of the TDD technique is to produce code and not to create a testing platform. The ability to test is an added benefit.<br />TDD is based on the idea that anything you build should be tested and if you are unable to test it, you should think twice about whether you really want to build it.<br />
  19. 19. “The single most important effect of practicing TDD is that it forces you as the developer to be the first consumer of your own API.”<br />Brian Button<br />
  20. 20. TDD Rules<br />You are not allowed to write any production code unless it is to make a failing unit test pass.<br />You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.<br />Via butunclebob.com<br />
  21. 21. What most programmers think about TDD when they are first introduced to the technique?<br />
  22. 22. Programmers respond:<br />"This is stupid!" <br />"It's going to slow me down”<br />“It's a waste of time and effort”<br />“It will keep me from thinking”<br />“It will keep me from designing”<br />“It will just break my flow”<br />Via butunclebob.com<br />
  23. 23. Defining Application’s Objective<br /> Understanding the application objectives is as<br /> important as coding your application. Here’s a<br />Lessons we can learn from a Master Carpenter: MeasureTwice, Cut Once!<br />
  24. 24. Defining Application’s Objective<br />You need to understand what you are developing<br />before you get started. In our case, we are building an application that will do the following:<br /> <br />Allow attendees to communicate with each other through twitter API. <br />The class will keep a list of tweets with #FlashAndTheCityhashtag<br />The class will check for updates of tweets often<br />  <br />
  25. 25. User Stories<br />A good approach to take to ensure the tasks are defined well is to follow Agile<br />software development mythology. The Agile mythologies talks about creating<br />one or more informal sentences in an everyday or business language, this type<br />of approach is known as a User Story. The User Story should be limited in<br />characters and should fit a small paper note card. The user stories are usually<br />written by the client in order to give direction to build the software. Think of<br />this list as your todo list.<br />In our case here are the User Stories:<br />Retrieve tweets with #FlashAndTheCityHashTag from Twitter API.<br />Have a service call to twitter and retrieve tweets every few seconds.<br />Login into user's twitter account and retrieve personal information.<br />Store user's information so user wouldn’t have to login again every time. <br />Post a tweet on twitter from a user <br />Add #FlashAndTheCityHashtag to a tweet so user wont have to type it every time and the application will be able to retrieve all tweets related to the conference.<br />Keep a list of tweets with the ability to add a tweet & remove a tweet.<br />
  26. 26. Creating the application<br />With the knowledge of what we need to develop we are ready to get started. The first step is to create the application open Eclipse or Flash Builder 4 Beta and create a new project name Companion (see instructions below).<br />Select File > New > Flex Project to create the project. <br />For the Project Name, type Companion, ensure you set the project as Desktop application type.<br />Click Finish. <br />
  27. 27. Creating your first Test Suite<br />A test suite is a composite of tests. It runs a collection of test cases. During development you can create a collection of tests packaged into test suite and once you are done, you can run the test suite to ensure your code is still working correctly after changes have been made.<br />To create a test suite, choose File > New > Test Suite class.<br />
  28. 28. Continue<br />After you select New Test Suite Class a wizard window opens up. Fill in the following information:<br />In the New Test Suite Class dialog box, name the class CompanionTestSuite.<br />Select New FlexUnit 4 Test. <br />Click Finish.<br />
  29. 29. Look at your Test Suite<br />Flash Builder 4 added the following class under the flexUnitTests folder:<br />packageflexUnitTests<br />{<br /> [Suite]<br /> [RunWith("org.flexunit.runners.Suite")]<br /> publicclassCompanionTestSuite<br /> {<br /> }<br />}<br /> <br />The Suite metadata tag indicates that the class is a suite. The RunWith tag instructs the test runner to execute the tests that follow it using a specific class. FlexUnit 4 is a collection of runners that will run a complete set of tests. You can define each runner to implement a specific interface. You can, for example, specify a different class to run the tests instead of the default runner built into FlexUnit 4.<br />
  30. 30. FlexUnit 4 Metadata<br />The FlexUnit 4 framework is based on metadata tags. So far you've seen [Suite], [Test], and [RunWith]. Here are some other common metadata tags:<br />[Ignore] - Causes the method to be ignored. You can use this tag instead of commenting out a method. <br />[Before] - Replaces the setup() method in FlexUnit 1 and supports multiple methods. <br />[After] - Replaces the teardown() method in FlexUnit 1 and supports multiple methods. <br />[BeforeClass] - Allows you to run methods before a test class. <br />[AfterClass] - Allows you to run methods after a test class. <br />
  31. 31. Add your first test case class<br />Next, you need to create a test case. A test case comprises the conditions you want to assert to verify a business requirement or a User Story. Each test case in FlexUnit 4 must be connected to a class. <br />Create the Test Case class:  <br />Choose File > New > Test Case Class.<br />Select New FlexUnit 4 Test.<br />Type flexUnitTests as the package.<br />Type TwitterHelperTesteras the name.<br />
  32. 32. Add a Reference <br />Important: Ensure that there is a reference in CompanionTestSuite.as to TwitterHelperTester:<br /> <br />packageflexUnitTests<br />{<br /> [Suite]<br /> [RunWith("org.flexunit.runners.Suite")]<br />publicclassCompanionTestSuite<br /> {<br />publicvartwitterHelperTester:TwitterHelperTester;<br /> }<br />}<br />
  33. 33. Implementing your User Stories<br />Retrieve Tweets User Story<br />We can start with the first User Story, Retrieve<br />tweets with #FlashAndTheCityHashTagfrom<br />Twitter API. <br />
  34. 34. Understand your goal<br />In our case we are testing that the service is working correctly. <br />We are using a public API that is maintained by Twitter and creating a Mashup application. <br />Using a well maintain API helps us creating our application quickly, however it also store a disadvantage that in any time Twitter may change their API and our application will stop working.<br />We are testing that the fail and success events are dispatching correctly and ensuring that the API is working, see the code below:<br />
  35. 35. testRetrieveTweetsBasedOnHashTag<br /> [Test(async,timeout="500")]<br />publicfunctiontestRetrieveTweetsBasedOnHashTag():void<br /> {<br />classToTestRef = newTwitterHelper();<br />varEVENT_TYPE:String = "retrieveTweets";<br />classToTestRef.addEventListener(EVENT_TYPE, Async.asyncHandler( this, handleAsyncEvnet, 500 ), false, 0, true );<br />classToTestRef.retrieveTweetsBasedOnHashTag("FlashAndTheCity”); <br /> }<br />privatefunctionhandleAsyncEvnet(event:Event, passThroughData:Object):void<br /> {<br />Assert.assertEquals( event.type, "retrieveTweets" );<br /> }<br />
  36. 36. Assertion methods<br />
  37. 37.
  38. 38. Working on the compilation errors<br />Save the file and now you see a compile time error:<br />Call to a possibly undefined method retrieveTweetsBasedOnHashTag through a reference with static type utils:TwitterHelper.<br />This is actually a good. The compiler is telling you what you need to do next. We can now create the method in TwitterHelper in order to get rid of the compiler error.<br />
  39. 39. Create TwitterHelper – write min code <br />packageutils<br />{<br />importflash.events.EventDispatcher;<br />importflash.events.IEventDispatcher;<br />publicclassTwitterHelperextendsEventDispatcher<br /> {<br />publicfunctionTwitterHelper(target:IEventDispatcher=null)<br /> {<br />super(target);<br /> }<br /> /**<br /> * Method to send a request to retrieve all the tweet with a HashTag<br /> * @paramhashTag defined hashtag to search<br /> * <br /> */ <br />publicfunctionretrieveTweetsBasedOnHashTag(hashTag:String):void<br /> {<br />// implement<br /> }<br /> }<br />}<br />
  40. 40. Run FlexUnit Tests<br />Compile the project and we don’t have any compile time errors and you can run the tests. Select the Run icon carrot and in the drop menu select FlexUnit Tests.<br />
  41. 41. Review the Results<br />Flash Builder opens a new window where the tests are run and shows the results of your test, see below:<br />1 total test was run <br />0 were successful <br />1 was a failure <br />0 were errors<br />0 were ignored<br />
  42. 42. Results view <br />
  43. 43. Change the Test from Fail to Pass<br />In order to pass the test you now need to write the actual code. At this point we wrote the test and once we write the code the test will succeed. I have implemented the code to call Twitter and retrieve results that includes #FlashAndTheCityhashtag<br />Write the code on TwitterHelper; retrieveTweetsBasedOnHashTag & onResults methods<br />
  44. 44. Write code<br />packageutils<br />{<br />importcom.adobe.serialization.json.JSON;<br />importflash.events.EventDispatcher;<br />importmx.rpc.events.FaultEvent;<br />importmx.rpc.events.ResultEvent;<br />importmx.rpc.http.HTTPService;<br />publicclassTwitterHelperextendsEventDispatcher<br /> {<br /> /**<br /> * Holds the service class <br /> */ <br />privatevarservice:HTTPService;<br />//--------------------------------------------------------------------------<br />//<br />// Default Constructor<br />//<br />//--------------------------------------------------------------------------<br />publicfunctionTwitterHelper() <br /> {<br />// implement<br /> }<br /> /**<br /> * Method to send a request to retrieve all the tweet with a HashTag<br /> * @paramhashTag defined hashtag to search<br /> * @url the twitter API url<br /> * <br /> */ <br />publicfunctionretrieveTweetsBasedOnHashTag(hashTag:String, url:String):void<br /> {<br /> service = newHTTPService();<br />service.url = url;<br />service.resultFormat = "text";<br />service.addEventListener(ResultEvent.RESULT, onResults);<br />varobject:Object = new Object();<br />object.q = hashTag;<br />service.send( object );<br />
  45. 45. Write code #2<br /> }<br />//--------------------------------------------------------------------------<br />//<br />// Event handlers<br />//<br />//--------------------------------------------------------------------------<br /> <br /> /**<br /> * Method to handle the result of a request to retrieve all the list <br /> * @param event<br /> * <br /> */<br />privatefunctiononResults(event:ResultEvent):void<br /> {<br />service.removeEventListener(ResultEvent.RESULT, onResults);<br />service.removeEventListener(FaultEvent.FAULT, onFault);<br />varrawData:String = String( event.result );<br />varobject:Object = JSON.decode( rawData );<br />varresults:Array = object.resultsas Array;<br />varcollection:Vector.<TweetVO> = new Vector.<TweetVO>;<br />results.forEach( functioncallback(item:*, index:int, array:Array):void {<br />vartweet:TweetVO = newTweetVO( item.from_user, item.from_user_id, item.geo, item.id, <br />item.profile_image_url, item.source, item.text, item.to_user, item.to_user_id );<br />collection.push( tweet );<br /> });<br />// dispatch an event that holds the results<br />this.dispatchEvent( newTwitterHelperSuccessEvent( collection ) );<br /> }<br /> }<br />}<br />
  46. 46. Run your test again<br />Run the test again and observe the results.<br />A test that does not fail succeeds <br />Click the Run Completed Button <br />Observe the Green Bar that indicates success<br />
  47. 47. Refactor<br />At this point, we can do a small refactoring to the test case and include the static method from the custom event instead of having the string attached, which will ensure our tests still pass in case we refactor the event type string, see code below:<br />classToTestRef = newTwitterHelper();<br />varEVENT_TYPE:String= TwitterHelperSuccessEvent.RETRIEVE_TWEETS;<br />
  48. 48. Refactor tests - tests have duplication that can become painful to maintain<br />In our case, we need to instantiating TwitterHelper in each test.<br />Granted, there are just two, but this will grow<br />We can solve this problem by using additional metadata provided by FlexUnit 4 called [Before] and [After]<br /> [Before] can be applied to any method that you wish called before each test.<br /> [After] will be called after each test<br />For good measure, let’s add a method name tearMeDown() and mark it with the [After] metadata. <br />The [After] method gives you a place to clean up from your test case.<br />In this case just set classToTestRef equal to null so the instance is available for garbage collection<br />In more complicated tests it is often crucial to remove listeners, etc. in this way. In our case TwitterHelper is already removing the listeners so we don’t need to do that, but many other times you will.<br />
  49. 49. Refactorthe actual code<br />We focus on passing the test and didn’t care that much about the code, however you may find out that the code is too complex and can be simplify by implementing a design pattern, or just adding some small modification. <br />For instance, I can add metadata so when you instantiate the class and add event listeners in MXML component you will get the event type available automatically. Add the code below to the TwitterHelperclass.<br />
  50. 50. My personal notes about TDD<br />Don’t use TDD for Micro-architecture User Gestures.<br />Usually avoid using TDD for testing GUI.<br />Use TDD for building APIs, frameworks, utilities and helpers.<br />Use TDD for testing services.<br />Use TDD for code that will be used on more than one application.<br />
  51. 51. Where to go from here?<br />Adobe Developer connectionhttp://www.adobe.com/devnet/flex/articles/flashbuilder4_tdd.html<br />Flash&Flex Magazine:http://elromdesign.com/blog/2010/01/19/flexunit-4-with-test-driven-development-article-on-ffdmag/<br />
  52. 52. Q&A<br />@EladElrom<br />