WordPress Websites for Engineers: Elevate Your Brand
Unit Testing ActionScript and Flex Code
1. Unit Testing ActionScript and Flex Michael Labriola | Senior Consultant, Digital Primates @mlabriola | labriola@digitalprimates.net
2. Who Am I? Michael Labriola Senior Consultant Digital Primates Client side architect specializing in Adobe Flex Architect and developer of Fluint Lead architect and developer of FlexUnit4.x Benevolent Dictator of the Spoon Framework Co-Author of Flex Training from the Source Series Team Mentor Fan of working code 2
3. Before We Begin This lab is broken into five main tasks with various exercises along the way In 90 minutes, if things go well, we will complete tasks one through four with some discussion along the way Task five is something I would strongly advise you take a bit of time to review later. It is a full rework of the application to be testable. The lab workbook and all lesson files are available for download At the end of several lessons there are ‘Advanced’ exercises. People will move at different rates through the content. If you find yourself done with a Task and have time, ponder the advanced exercise they will help demonstrate points in a Socratic way They can be treated as thought exercises but work better if you actually try to implement 3
4. Types of Testing - Unit Unit Testing - Our concern in this lab Unit testing involves testing the smallest units of code A single object It requires that the object be isolated. The test result should not be able to be affected by other objects It should not be affected by global state When a unit test fails the source of the error should be immediately clear This requirement for isolation means that some code cannot be unit tested Axiom - You can only unit test testable code Creating testable code is both a question of implementation and of architecture Many people want to unit test but fail In my experience, this is usually because the code they wish to test is not testable in units 4
5. Types of Testing - Integration Integration Testing Involves testing several (ideally tested) units together Very important part of testing You need to know that individual objects work together properly Failures are not as clear When an integration test fails, there are (n) places it could have failed As a general rule, the moment we discuss any of the following words, we are discussing some form of integration test: Asynchronous Server Lifecycle DisplayList 5
6. Types of Testing - Functional Allows you to record and playback interactions with an application Extremely important; ensures that the application works to specification Many units need to be working before you can produce a single test Failures are very unclear Any number of units could be responsible for the failure Many tools available: Flex Monkey – Open Source Test Complete RIATest HP QTP And more 6
8. Object Graphs To understand unit testing we need understand object graphs There are two types of objects we are concerned about Branch and Leaf Leaf Nodes have no dependencies on other objects in your code (they will have dependencies on simple types and some flash player objects) Trivial to test Branch Nodes have dependencies on other objects More difficult and sometimes impossible to test 8
9. Creating Objects You will always have both types in your system, however, we often have too many dependencies because we forget some simple things: An object is supposed to have one responsibility. Single Responsibility Principle. Objects with (n) responsibilities will be much harder to test effectively Second objects shouldn’t reach into each other. It breaks encapsulation Don’t violate the Law of Demeter myObject.childObject.grandChildObject.property 9
11. Testing Framework FlexUnit 4 is a unit testing framework You don’t need a framework to test You already test each time you walk through the same actions to vet a piece of code Testing frameworks only exist to: Automate this effort so the tests can be run again and again easily Standardize the way tests are constructed so they are understandable to others 11
12. Assertions Assertions are a tool used to reveal whether or not a piece of code is working as expected. They take the form of a strong statement indicating the result. For example, if you add the numbers 2 and 3. result = 2 + 3; You can assert that the result is 5. You do so as you are sure that no other answer is satisfactory and that a different answer is just plain wrong. assertEquals( 5, result ); If this assertion is not true, meaning that result is not equal to 5, then you can conclude that the plus operator no longer works correctly in all cases. This is the basis of testing. 12
13. Test A Test is just a public method of an object The method is decorated by a special [Test] metadata which allows FlexUnit 4 to recognize it as test [Test] public function shouldSeeBlueSky():void { varsky:Sky = new Sky(); assertEquals( “blue”, sky.color ); } Tests contain one (preferable) or more assertions indicating your belief about the state of the object under test or the result of a method invoked on the object Each test is discrete. It should not depend on other tests or the order the tests are run. 13
14. Test Case A Test Case is a collection of related Tests in a single class [Test] public function shouldSeeBlueSky():void { varsky:Sky = new Sky(); assertEquals( “blue”, sky.color ); } [Test] public function shouldNotSeeClouds():void { varsky:Sky = new Sky(); assertNull(sky.clouds); } 14
15. Test Case Setup As all tests in a single Test Case should be related, they often can share setup The combination of the setup/environment needed to run a test is called a Test Fixture FlexUnit 4 facilitates sharing test fixtures by allowing you to mark a method with Before or After metadata. This indicates the method should be run before or after every test method. [Before] public function andTheSkyWasCreated():void { sky = new Sky(); } [After] public function letItFall():void { sky = null; } 15
16. Test Case Rules FlexUnit 4 offers one more way to configure the test case fixture, rules. You can think of rules as a way to move things that would happen in the Before and After into a separate object. This makes it easier to share this configuration code amongst multiple test cases [Rule] public varcreateAndDestroySky:CreateAndDestroySkyRule = new CreateAndDestroySkyRule(); 16
17. Test Suite A Test Suite is a collection of Test Cases and other Test Suites package flexUnitTests { [Suite] [RunWith("org.flexunit.runners.Suite")] public class CurrencyConverterSuite { public var test1:ClearSkyTests; public var test2:StormySkyTests; } } 17
19. Matchers The process of performing multiple assertions can become complicated Imagine a scenario where you need to verify that 2 points are identical [Test] public function shouldBeTheSamePoint():void { assertEquals( pt1.x, pt2.x ); assertEquals( pt1.y, pt2.y ); assertEquals( pt1.z, pt2.x ); } At some point your test cases become littered with all of the work required to do the assertions To address this problem, FlexUnit works with something called matchers that allow you to move this work into a separate object 19
20. Hamcrest Using matchers, the code can look more like this: [Test] public function shouldBeTheSamePoint():void { assertThat( pt1, isSamePoint( pt2 ) ); } The code becomes more readable and the matching logic is contained elsewhere. There is a collection of matchers that can be used with FlexUnit as well as any ActionScript project that can use specialized matching, it is called Hamcrest-as3 For more information: https://github.com/drewbourne/hamcrest-as3 20
23. Branches versus Nodes We talked about branches in the abstract, but here is something more concrete. Even though we extracted the PercentChangeFormatter from MarketInfo, it is still a branch node, not a leaf node 23 MarketInfo PercentChangeFormatter NumberFormatter
24. Combinatorial If you aren’t careful with these sorts of dependencies, you end up with combinatorial tests. This results in a lot of test duplication… technically this is because you can’t identify independent variables. The PercentChangeFormatter really just modifies the String returned from the NumberFormatter a little. As they exist now we really end up testing the both of these objects together… which is an integration test… 24 PercentChangeFormatter NumberFormatter
26. Seams and Mocks The cleanest way to deal with this is to create a seam. If we provide the needed NumberFormatter to the PercentChangeFormatter, we create a seam What can we do with that seam? We could build the PercentChangeFormatter with a substitute NumberFormatter This will eliminate the combinations and allow us to test only one class (a unit) There are two types of substitutes we can use… fakes and mocks Fakes are just dumb objects that conform to the same interface Mocks are intelligent objects that keep track of what happened to them and know how they should respond For this Task we will use one of many available mocking frameworks, named Mockolate. 26
28. Additional Resources 28 Google Testing Blog http://googletesting.blogspot.com/ FlexUnit http://flexunit.org/ FlexUnit Tutorials http://tutorials.digitalprimates.net/flexunit.html Hamcrest https://github.com/drewbourne/hamcrest-as3 Mockolate http://mockolate.org/ My Blog http://www.digitalprimates.net/author/codeslinger/