Accessibility

Table of Contents

Unit testing with mock objects in ActionScript 3.0

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.