Unit testing with mock objects in ActionScript 3.0

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
Required Products
Flex Builder (Download trial)
Sample Files
User Level


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:



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; } } }



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


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:




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:




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:


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:



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()); } } }



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:

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.