SlideShare a Scribd company logo
1 of 29
Unit Testing ActionScript and Flex Michael Labriola  |  Senior Consultant, Digital Primates @mlabriola | labriola@digitalprimates.net
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
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
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
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
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
Exercise 1.1 7
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
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
Exercise 1.2 and 1.3 10
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
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
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
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
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
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
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
Exercise 2.1 and 2.2 18
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
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
Exercise 2.3 21
Exercise 3.1-3.2 22
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
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
Exercise 4.1 25
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
Exercise 4.2 27
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/
29

More Related Content

What's hot

Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010Stefano Paluello
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Something for Nothing
Something for NothingSomething for Nothing
Something for NothingKevlin Henney
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Codeslicklash
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesDavid Rodenas
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 

What's hot (17)

Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Easy mock
Easy mockEasy mock
Easy mock
 
django
djangodjango
django
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD Techniques
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 

Viewers also liked

Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audiencemichael.labriola
 
Archives of the Columbia-Princeton Electronic Music Center
Archives of the Columbia-Princeton Electronic Music CenterArchives of the Columbia-Princeton Electronic Music Center
Archives of the Columbia-Princeton Electronic Music CenterNick Patterson
 
2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Componentsmichael.labriola
 
Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy michael.labriola
 
Flex 4 components from the firehose
Flex 4 components from the firehoseFlex 4 components from the firehose
Flex 4 components from the firehosemichael.labriola
 
Les nouveautés du Windows Runtime 8.1
Les nouveautés du Windows Runtime 8.1Les nouveautés du Windows Runtime 8.1
Les nouveautés du Windows Runtime 8.1Microsoft
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 

Viewers also liked (8)

Blaze Ds Slides
Blaze Ds SlidesBlaze Ds Slides
Blaze Ds Slides
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audience
 
Archives of the Columbia-Princeton Electronic Music Center
Archives of the Columbia-Princeton Electronic Music CenterArchives of the Columbia-Princeton Electronic Music Center
Archives of the Columbia-Princeton Electronic Music Center
 
2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components
 
Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy
 
Flex 4 components from the firehose
Flex 4 components from the firehoseFlex 4 components from the firehose
Flex 4 components from the firehose
 
Les nouveautés du Windows Runtime 8.1
Les nouveautés du Windows Runtime 8.1Les nouveautés du Windows Runtime 8.1
Les nouveautés du Windows Runtime 8.1
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 

Similar to Unit Testing ActionScript and Flex Code

Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminardunglinh111
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)Amr E. Mohamed
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
FlexUnit 4 for contributors
FlexUnit 4 for contributorsFlexUnit 4 for contributors
FlexUnit 4 for contributorsmichael.labriola
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxKnoldus Inc.
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitAmr E. Mohamed
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 

Similar to Unit Testing ActionScript and Flex Code (20)

Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Effective unit testing
Effective unit testingEffective unit testing
Effective unit testing
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
FlexUnit 4 for contributors
FlexUnit 4 for contributorsFlexUnit 4 for contributors
FlexUnit 4 for contributors
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 
Presentation
PresentationPresentation
Presentation
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 

More from michael.labriola

Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Renderingmichael.labriola
 
Randori design goals and justification
Randori design goals and justificationRandori design goals and justification
Randori design goals and justificationmichael.labriola
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audiencemichael.labriola
 
Flex 4 Component Development
Flex 4 Component DevelopmentFlex 4 Component Development
Flex 4 Component Developmentmichael.labriola
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Watersmichael.labriola
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructuremichael.labriola
 

More from michael.labriola (12)

Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Rendering
 
Randori design goals and justification
Randori design goals and justificationRandori design goals and justification
Randori design goals and justification
 
Talking trash
Talking trashTalking trash
Talking trash
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audience
 
Apocalypse Soon
Apocalypse SoonApocalypse Soon
Apocalypse Soon
 
Flex 4 Component Development
Flex 4 Component DevelopmentFlex 4 Component Development
Flex 4 Component Development
 
Any Which Array But Loose
Any Which Array But LooseAny Which Array But Loose
Any Which Array But Loose
 
Air Drag And Drop
Air Drag And DropAir Drag And Drop
Air Drag And Drop
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructure
 
Dense And Hot 360 Flex
Dense And Hot 360 FlexDense And Hot 360 Flex
Dense And Hot 360 Flex
 
Dense And Hot Web Du
Dense And Hot  Web DuDense And Hot  Web Du
Dense And Hot Web Du
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

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/
  • 29. 29

Editor's Notes

  1. Image Copyright Wenger