Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
Review and Checkout
Adobe Developer Connection / ActionScript Technology Center /

Unit testing with mock objects in ActionScript 3.0

by Jason Peters

Jason Peters
  • International Game Technology

by Paulo Caroli

Paulo Caroli
  • ThoughtWorks

Content

  • Examining the SUT and DOC code
  • Using mock objects for unit testing

Modified

19 January 2009

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScriptFlash Buildertestingunit testing
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

Requirements

Prerequisite knowledge

You should have a good understanding of ActionScript 3.0 and object-oriented principles, as well as some knowledge of unit testing.

 

Additional required products

Mock4AS

FlexUnit

User level

Advanced

Required products

  • Flex Builder (Download trial)

Sample files

  • mock-samples.zip (8 KB)

When you perform unit tests, it is not always possible to verify that an object does what you expect by examining that object directly. Instead, you may need to examine the collaborations between objects. Mock object frameworks simplify behavior verification—the process of verifying the interaction between dependent components.

This article is intended for developers interested in adding behavior verification to their unit tests. It discusses the role of behavior verification in unit testing and introduce the basics of Mock4AS, a lightweight mock object framework for ActionScript 3.0.

Behavior verification's role in unit testing

In unit testing lingo, the object you are testing is called the System Under Test (SUT for short). Each object that the SUT depends on to fulfill its tasks is called a Depended On Component (DOC for short).

For example, consider an object that is used to generate a greeting message when a user logs on to your website. For localization purposes, this Greeting object uses a Translator object to translate "hello" into the desired language. You want to test the Greeting object, so it is the SUT. This object depends on the Translator to get the right message, so the Translator is the DOC.

To verify that the SUT collaborates with the DOC in the way you expect, you can replace the usual DOC with a test double, called a mock. You then tell the mock what it should expect from the SUT. Once those expectations are set, you exercise the SUT by calling methods on it. In turn, the SUT calls methods on the mock. After you are finished exercising the SUT, you query the mock to see if it was used in the way you expected.

Mock objects frameworks provide the necessary mechanisms to set behavior, record incoming method calls, and verify that the methods were called as expected.

Examining the SUT and DOC code

Before you start to use mock objects, take a look at the Greeting example's functional code. In this example, there is a custom Greeting class that depends on an implementation of Translator (Translator is an interface).

The Greeting class provides behavior to say "Hello" in any language. Greeting uses a Translator implementation to translate "Hello" from English to the selected language. Here is the typical usage of the Greeting class:

var translator:Translator = new TranslatorImpl(); var greeter:Greeting = new Greeting(translator); var msg:String = greeter.sayHello("Portuguese", "Paulo");

At construction time, the Greeting component receives an instance of the TranslatorImpl class, a concrete implementation of the Translator interface. In your tests, you will need to use a mock object that also implements the Translator interface.

Here is the code for Greeting and Translator:

Greeting.as

package org.mock4as.samples.greeting { public class Greeting { private var translator:Translator; public function Greeting(translator:Translator){ this.translator = translator; } public function sayHello(language:String, name:String):String{ return translator.translate("English", language, "Hello") + " " + name; } } }

Translator.as

package org.mock4as.samples.greeting { public interface Translator { function translate(from:String, to:String, word:String):String } }

Now that you know how the Greeting class depends on Translator, you can apply a mock object to verify that the Greeting class uses the Translator object the way you expect.

Using mock objects for unit testing

Using mock objects for unit testing involves the following steps:

  1. Create a Mock class.
  2. Instantiate the Mock.
  3. Set expectations and behavior for the Mock.
  4. Inject the Mock.
  5. Exercise the System Under Test (SUT).
  6. Verify the Mock expectations.

The following steps will guide you through the unit test code (using mock objects) for the Greeting example. FlexUnit and Mock4AS are, respectively, the unit test and the mock object frameworks used in this example. Before running the sample code, install FlexUnit and Mock4AS after you download them. (See links at the beginning of the article.)

1. Create the Mock

To use Mock4AS you must create a class that either extends the org.moc4as.Mock class or uses it in composition. For simplicity's sake, this article's code example illustrates only subclassing org.moc4as.Mock. (You can use the Mock in composition following the same principles of composition for any object. Check the Mock4AS project page for the equivalent composition example.)First, create a new class that extends org.mock4as.Mock and implements the interface of the component you want to mock. For example:

public class MockTranslator extends Mock implements Translator {}

Next, implement the methods of the interface you are mocking with calls to the mock's record() method. This sets up the structure to record calls made to the dependant component. In this case, you want to record calls to the translate method along with the arguments passed to it. For this example, the MockTranslator class would have the following implementation for translate:

public function translate(from:String, to:String, word:String):String { record("translate", from, to, word); return expectedReturnFor(); }

With this implementation of the translate method, the Mock4AS framework will make a note that the method and its parameters have been called. Also the Mock4AS framework will return the value that was set for the translate method. The record() and expectedReturnFor() methods provide the link to the expectations and behavior set for the mock object (more details on this are in the following sections).

Here is the full code for the MockTranslator class:

import org.mock4as.Mock; class MockTranslator extends Mock implements Translator { public function translate(from:String, to:String, word:String):String { record("translate", from, to, word); return expectedReturnFor("translate"); } }

2. Instantiate the Mock object

Now that you have created the MockTranslator class, you need to instantiate and use it. You instantiate a Mock in the same way you instantiate any other ActionScript class, using the new operator. Typically, this is done in a unit test that exercises your SUT.

var Mock:mockTranslator = new MockTranslator();

3. Set expectations and behavior for the Mock

To verify that your Mock has been invoked the way you expect, you need to set its expectations. You do this by first invoking the Mock API’s expects() method. Although the expects() method must be called first, the Mock API provides several methods to set expectations. Here are some of the methods you can use:

  • expects(methodName:String): Tells the Mock the name of the expected method call
  • times(numOfTimes:int): Sets the number of times a particular method should be called
  • withArgs(arg1, arg2, ...argN): Tells the Mock what arguments should be passed to a particular method

Because these methods return a reference to the Mock you are setting expectations for, you can chain the method calls for readability. For example, to tell a Mock to expect translate("English","Portuguese", "Hello") to be called once you would write:

mockTranslator.expects("translate").times(1).withArgs("English","Portuguese","Hello");

Mock4AS also provides capabilities to set up behavior for your Mock objects. You set behavior the same way as in the earlier code example with the addition of a call to the Mock's willReturn() method:

mockTranslator.expects("translate").times(1).withArgs("English","Portuguese","Hello").willReturn("Ola").times(1);

This example tells the Mock to return the value "Ola" when the translate method is called with the arguments "English", "Portuguese", and "Hello". At this point you can test how the greeter responds to this input.

Note: While this example passes a String argument ("Ola"), the willReturn() method can be used to pass any type of object.

You can use willReturn() to provide all types of data, even invalid data. This can help you verify how an object reacts to invalid data. You can also configure the Mock to throw an error with willReturn(new Error()). You can use this to test how the SUT handles errors raised by the DOC.

4. Inject the Mock

At this point, you have a Mock instance, mockTranslator, and you have told it what to expect and how to behave. Now you need to tell the Greeting object to use the mockTranslator instance. The following code shows mockTranslator being injected into Greeting during construction time:

var greeter:Greeting = new Greeting(mockTranslator);

At construction time, the Greeting component receives mockTranslator, a concrete implementation of the Translator interface. Now, when the greeter calls its Translator it will be calling mockTranslator, which will record the incoming method calls.

5. Exercise the SUT

Now you need to exercise the SUT. Simply call the method that you expect to invoke the mock. Essentially, you are telling your SUT to run. Later you will verify that when the SUT ran, it used the mock the way you expect. In this example, you will exercise the Greeting component's sayHello() method. To do this, simply call the sayHello() method on greeter:

greeter.sayHello("Portuguese", "Paulo");

6. Verify the Mock expectations

The last step is to verify the mock expectations. You have told mockTranslator to expect its translate method to be called one time with the arguments "English", "Portuguese", and "Hello" (in that order). Now that you have exercised the Greeting class by calling its sayHello() method, you want to verify that the greeter has called mockTranslator according to your expectations using the mockTranslator.success() method: mockTranslator.success();

The success() method checks to see if the methods called match the expectations you have previously set. If the mock is invoked the way you expected success() returns true, otherwise success() will return false.

Typically, you would call the success() method within a test case assertion as follows:

assertTrue(mockTranlator.errorMessage(),mockTranlator.success());

If success() returns false, then the errorMessage() method returns a string that describes why the verification failed. Here are some possible reasons for failure:

  • Methods were called that were not expected
  • Methods that were expected were not called
  • An expected method was called with arguments that were not expected
  • Methods were not called in the order in which they were expected

Note: This example uses the FlexUnit test framework. However, Mock4AS can be used with any ActionScript 3.0 unit testing framework.

Here is the complete Greeting Unit Test sample code:

GreetingTest.as

package org.mock4as.samples.greeting { import flexunit.framework.TestCase; import flexunit.framework.TestSuite; import org.mock4as.Mock; public class GreetingTest extends TestCase { public function GreetingTest(methodName : String) { super(methodName); } public function testGreetingInAnyLanguage():void { // create the Mock var Mock:mockTranslator = new MockTranslator(); // set expectations and behavior mockTranslator.expects("translate").withArgs("English","Portuguese","Hello").andReturn("Ola"); // inject the Mock var greeter:Greeting = new Greeting(mockTranslator); // exercise the class you are testing greeter.sayHello("Portuguese", "Paulo")); // verify Mock behavior assertTrue(mockTranslator.errorMessage(),mockTranslator.success()); } } }

MockTranslator.as

import org.mock4as.Mock; import org.mock4as.samples.greeting.Translator; class MockTranslator extends Mock implements Translator { public function translate(from:String, to:String, word:String):String { record("translate", from, to, word); return expectedReturnFor("translate"); } }

Where to go from here

While not all tests need mock objects, they do address several needs you are likely to encounter while unit testing. The example introduced in this article was fairly simple, but you can use the same techniques to help you in more complex testing efforts. In making Mock4AS, we tried to build a framework with the same behavior and API as many of the more popular mock object frameworks commonly in use.

For more on unit testing ActionScript 3.0 projects, read Neil Webb's article, Unit testing and Test Driven Development (TDD) for Flex and ActionScript 3.0.

For more on mock objects and test code, check out the following references:

  • Mocks Aren't Stubs (Martin Fowler)
  • xUnit Test Patterns: Refactoring Test Code (Gerard Meszaros)

While mock objects allow you to test objects in isolation (unit test), functional tests are intended to help you verify that a system, as a whole, functions as intended. For more information on automated functional test for Flex applications, read Paulo's article, Writing and running functional tests for Flash with Selenium RC.

More Like This

  • Six reasons to use ActionScript 3.0
  • Creating a preloader in Flash
  • Introduction to event handling in ActionScript 3.0
  • ActionScript 3 Design Patterns excerpt: Factory method and MVC
  • Essential ActionScript 3 excerpt: Display and interactivity
  • ActionScript 3.0 overview
  • ActionScript 3 Cookbook excerpts: From custom classes to the rendering model
  • Flash iOS Apps Cookbook excerpt: ActionScript optimization
  • Introduction to Robotlegs – Part 3: Services
  • Introduction to Robotlegs – Part 2: Models

Products

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

Ad Choices

Reviewed by TRUSTe: site privacy statement