Packageasunit.framework
Classpublic class TestCase
InheritanceTestCase Inheritance Assert Inheritance flash.events.EventDispatcher
ImplementsTest
SubclassesAsynchronousTestCase, RemotingTestCase, TestCaseExample, TestSuite

A test case defines the fixture to run multiple tests. To define a test case
1) implement a subclass of TestCase
2) define instance variables that store the state of the fixture
3) initialize the fixture state by overriding setUp
4) clean-up after a test by overriding tearDown.
Each test runs in its own fixture so there can be no side effects among test runs. Here is an example:
     public class MathTest extends TestCase {
          private var value1:Number;
          private var value2:Number;
     
          public function MathTest(methodName:String=null) {
             super(methodName);
          }
     
          override protected function setUp():void {
             super.setUp();
             value1 = 2;
             value2 = 3;
          }
     }
     
For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling assertTrue with a boolean, or assertEquals with two primitive values that should match.
        public function testAdd():void {
            var result:Number = value1 + value2;
            assertEquals(5, result);
        }
     
There are three common types of test cases:
  1. Simple unit test
  2. Visual integration test
  3. Asynchronous test

View the examples.



Protected Properties
 PropertyDefined by
  context : DisplayObjectContainer
TestCase
  fName : String
TestCase
  isComplete : Boolean
TestCase
  result : TestListener
TestCase
  testMethods : Array
TestCase
Public Methods
 MethodDefined by
  
TestCase(testMethod:String = null)
Constructs a test case with the given name.
TestCase
 Inherited
assertEquals(... args):void
[static] Asserts that two objects are equal.
Assert
 Inherited
assertEqualsArrays(... args):void
[static] Asserts that two arrays have the same length and contain the same objects in the same order.
Assert
 Inherited
[static] Asserts that two arrays have the same length and contain the same objects.
Assert
 Inherited
assertEqualsFloat(... args):void
[static] Asserts that two numerical values are equal within a tolerance range.
Assert
 Inherited
assertFalse(... args):void
[static] Asserts that a condition is false.
Assert
 Inherited
assertNotNull(... args):void
[static] Asserts that an object isn't null.
Assert
 Inherited
assertNotSame(... args):void
[static] Asserts that two objects do not refer to the same object.
Assert
 Inherited
assertNull(... args):void
[static] Asserts that an object is null.
Assert
 Inherited
assertSame(... args):void
[static] Asserts that two objects refer to the same object.
Assert
 Inherited
assertThrows(errorType:Class, block:Function):void
[static] Asserts that the provided block throws an exception that matches the type provided.
Assert
 Inherited
assertTrue(... args):void
[static] Asserts that a condition is true.
Assert
  
TestCase
  
asyncOperationTimeout(async:AsyncOperation, duration:Number):void
TestCase
  
Counts the number of test cases executed by run(TestResult result).
TestCase
 Inherited
fail(message:String):void
[static] Fails a test with the given message.
Assert
  
getContext():DisplayObjectContainer
Returns the visual DisplayObjectContainer that will be used by addChild and removeChild helper methods.
TestCase
  
TestCase
  
getIsComplete():Boolean
TestCase
  
getName():String
Gets the name of a TestCase
TestCase
  
TestCase
  
TestCase
  
run():void
A convenience method to run this test, collecting the results with either the TestResult provided or a default, new TestResult object.
TestCase
  
runBare():void
Runs the bare test sequence.
TestCase
  
setContext(context:DisplayObjectContainer):void
TestCase
  
setName(name:String):void
Sets the name of a TestCase
TestCase
  
setResult(result:TestListener):void
TestCase
  
toString():String
Returns a string representation of the test case
TestCase
Protected Methods
 MethodDefined by
  
addAsync(handler:Function = null, duration:Number):Function
Called from within setUp or the body of any test method.
TestCase
  
addChild(child:DisplayObject):DisplayObject
Helper method for testing DisplayObjects.
TestCase
  
cleanUp():void
Override this method in Asynchronous test cases or any other time you want to perform additional member cleanup after all test methods have run
TestCase
  
Creates a default TestResult object
TestCase
  
removeChild(child:DisplayObject):DisplayObject
Helper method for removing added DisplayObjects.
TestCase
  
runTearDown():void
TestCase
  
setTestMethods(methodNodes:XMLList):void
TestCase
  
setUp():void
Sets up the fixture, for example, instantiate a mock object.
TestCase
  
tearDown():void
Tears down the fixture, for example, delete mock object.
TestCase
Protected Constants
 ConstantDefined by
  DEFAULT_TIMEOUT : int = 1000
[static]
TestCase
  PRE_SET_UP : int = 0
[static]
TestCase
  RUN_METHOD : int = 2
[static]
TestCase
  SET_UP : int = 1
[static]
TestCase
  TEAR_DOWN : int = 3
[static]
TestCase
Property detail
contextproperty
protected var context:DisplayObjectContainer
fNameproperty 
protected var fName:String
isCompleteproperty 
protected var isComplete:Boolean
resultproperty 
protected var result:TestListener
testMethodsproperty 
protected var testMethods:Array
Constructor detail
TestCase()constructor
public function TestCase(testMethod:String = null)

Constructs a test case with the given name. Be sure to implement the constructor in your own TestCase base classes. Using the optional testMethod constructor parameter is how we create and run a single test case and test method.

Parameters
testMethod:String (default = null)
Method detail
addAsync()method
protected function addAsync(handler:Function = null, duration:Number):Function

Called from within setUp or the body of any test method. Any call to addAsync, will prevent test execution from continuing until the duration (in milliseconds) is exceeded, or the function returned by addAsync is called. addAsync can be called any number of times within a particular test method, and will block execution until each handler has returned. Following is an example of how to use the addAsync feature:

          public function testDispatcher():void {
              var dispatcher:IEventDispatcher = new EventDispatcher();
              // Subscribe to an event by sending the return value of addAsync:
              dispatcher.addEventListener(Event.COMPLETE, addAsync(function(event:Event):void {
                  // Make assertions nsideyour async handler:
                  assertEquals(34, dispatcher.value);
              }));
          }
          
If you just want to verify that a particular event is triggered, you don't need to provide a handler of your own, you can do the following:
          public function testDispatcher():void {
              var dispatcher:IEventDispatcher = new EventDispatcher();
              dispatcher.addEventListener(Event.COMPLETE, addAsync());
          }
          
If you have a series of events that need to happen, you can generally add the async handler to the last one. The main thing to remember is that any assertions that happen outside of the initial thread of execution, must be inside of an addAsync block.

Parameters
handler:Function (default = null)
 
duration:Number

Returns
Function
addChild()method 
protected function addChild(child:DisplayObject):DisplayObject

Helper method for testing DisplayObjects. This method allows you to more easily add and manage DisplayObject instances in your TestCase. If you are using the regular TestRunner, you cannot add Flex classes. If you are using a FlexRunner base class, you can add either regular DisplayObjects or IUIComponents. Usually, this method is called within setUp, and removeChild is called from within tearDown. Using these methods, ensures that added children will be subsequently removed, even when tests fail. Here is an example of the addChild method:

          private var instance:MyComponent;
        
          override protected function setUp():void {
              super.setUp();
              instance = new MyComponent();
              instance.addEventListener(Event.COMPLETE, addAsync());
              addChild(instance);
          }
        
          override protected function tearDown():void {
              super.tearDown();
              removeChild(instance);
          }
        
          public function testParam():void {
              assertEquals(34, instance.value);
          }
        

Parameters
child:DisplayObject

Returns
DisplayObject
asyncOperationComplete()method 
public function asyncOperationComplete(async:AsyncOperation):voidParameters
async:AsyncOperation
asyncOperationTimeout()method 
public function asyncOperationTimeout(async:AsyncOperation, duration:Number):voidParameters
async:AsyncOperation
 
duration:Number
cleanUp()method 
protected function cleanUp():void

Override this method in Asynchronous test cases or any other time you want to perform additional member cleanup after all test methods have run

countTestCases()method 
public function countTestCases():int

Counts the number of test cases executed by run(TestResult result).

Returns
int
createResult()method 
protected function createResult():TestResult

Creates a default TestResult object

Returns
TestResult

See also

getContext()method 
public function getContext():DisplayObjectContainer

Returns the visual DisplayObjectContainer that will be used by addChild and removeChild helper methods.

Returns
DisplayObjectContainer
getCurrentMethod()method 
public function getCurrentMethod():String

Returns
String
getIsComplete()method 
public function getIsComplete():Boolean

Returns
Boolean
getName()method 
public function getName():String

Gets the name of a TestCase

Returns
String — returns a String
getResult()method 
public function getResult():TestListener

Returns
TestListener
getTestMethods()method 
public function getTestMethods():Array

Returns
Array
removeChild()method 
protected function removeChild(child:DisplayObject):DisplayObject

Helper method for removing added DisplayObjects. Update: This method should no longer fail if the provided DisplayObject has already been removed.

Parameters
child:DisplayObject

Returns
DisplayObject
run()method 
public function run():void

A convenience method to run this test, collecting the results with either the TestResult provided or a default, new TestResult object. Expects either: run():void // will return the newly created TestResult run(result:TestResult):TestResult // will use the TestResult that was passed in.

See also

runBare()method 
public function runBare():void

Runs the bare test sequence.


Throws
— if any exception is thrown
runTearDown()method 
protected function runTearDown():void
setContext()method 
public function setContext(context:DisplayObjectContainer):voidParameters
context:DisplayObjectContainer
setName()method 
public function setName(name:String):void

Sets the name of a TestCase

Parameters
name:String — The name to set
setResult()method 
public function setResult(result:TestListener):voidParameters
result:TestListener
setTestMethods()method 
protected function setTestMethods(methodNodes:XMLList):voidParameters
methodNodes:XMLList
setUp()method 
protected function setUp():void

Sets up the fixture, for example, instantiate a mock object. This method is called before each test is executed. throws Exception on error.


Example
This method is usually overridden in your concrete test cases:
          private var instance:MyInstance;
          
          override protected function setUp():void {
              super.setUp();
              instance = new MyInstance();
              addChild(instance);
          }
          

tearDown()method 
protected function tearDown():void

Tears down the fixture, for example, delete mock object. This method is called after a test is executed - even if the test method throws an exception or fails. Even though the base class TestCase doesn't do anything on tearDown, It's a good idea to call super.tearDown() in your subclasses. Many projects wind up using some common fixtures which can often be extracted out a common project TestCase. tearDown is not called when we tell a test case to execute a single test method.


Throws
— on error.

Example
This method is usually overridden in your concrete test cases:
          private var instance:MyInstance;
          
          override protected function setUp():void {
              super.setUp();
              instance = new MyInstance();
              addChild(instance);
          }
          
          override protected function tearDown():void {
              super.tearDown();
              removeChild(instance);
          }
          

toString()method 
public override function toString():String

Returns a string representation of the test case

Returns
String
Constant detail
DEFAULT_TIMEOUTconstant
protected static const DEFAULT_TIMEOUT:int = 1000
PRE_SET_UPconstant 
protected static const PRE_SET_UP:int = 0
RUN_METHODconstant 
protected static const RUN_METHOD:int = 2
SET_UPconstant 
protected static const SET_UP:int = 1
TEAR_DOWNconstant 
protected static const TEAR_DOWN:int = 3
Examples

// Assume we are testing a class that looks like this:
package utils {
    
    public class MathUtil {
        
        // Add one to the number provided:
        public function addOne(num:Number):Number {
            return num + 1;
        }
    }
}


// This is a test case for the class above:
package utils {

    import asunit.framework.TestCase;

    public class MathUtilTest extends TestCase {
        private var mathUtil:MathUtil;

        public function MathUtilTest(methodName:String=null) {
            super(methodName)
        }

        override protected function setUp():void {
            super.setUp();
            mathUtil = new MathUtil();
        }

        override protected function tearDown():void {
            super.tearDown();
            mathUtil = null;
        }

        public function testInstantiated():void {
            assertTrue("mathUtil is MathUtil", mathUtil is MathUtil);
        }

        public function testAddOne():void {
            assertEquals(5, mathUtil.addOne(4));
        }
    }
}

For the purpose of the following test example, we'll be using a Runner that
looks like this:

package {
    import asunit.textui.TestRunner;
    import controls.ViewComponentTest;
    
    public class SomeProjectRunner extends TestRunner {

        public function SomeProjectRunner() {
            // start(clazz:Class, methodName:String, showTrace:Boolean)
            // NOTE: sending a particular class and method name will
            // execute setUp(), the method and NOT tearDown.
            // This allows you to get visual confirmation while developing
            // visual entities
            start(ViewComponentTest, 'testGoToHalfSize', TestRunner.SHOW_TRACE);
        }
    }
}

The following Component is a visual component whose primary feature
is the 'goToHalfSize' method.

package controls {
    
    import flash.display.Sprite;
    import flash.events.Event;
    
    public class ViewComponent extends Sprite {
        
        private var _width:Number;
        private var _height:Number;
        
        public function ViewComponent() {
            _width = 640;
            _height = 480;
        }
        
        public function draw():void {
            graphics.clear();
            graphics.beginFill(0xFFCC00);
            graphics.drawRect(0, 0, width, height);
            graphics.endFill();
        }
        
        public function goToHalfSize():void {
            width = Math.round(width / 2);
            height = Math.round(height / 2);
            draw();
        }
        
        override public function set width(width:Number):void {
            _width = width;
        }

        override public function get width():Number {
            return _width;
        }

        override public function set height(height:Number):void {
            _height = height;
        }

        override public function get height():Number {
            return _height;
        }
    }
}

And finally, the test case that will validate the ViewComponent class and
it's goToHalfSize method.

package controls {

    import asunit.framework.TestCase;

    public class ViewComponentTest extends TestCase {
        private var instance:ViewComponent;

        public function ViewComponentTest(methodName:String=null) {
            super(methodName)
        }

        override protected function setUp():void {
            super.setUp();
            instance = new ViewComponent();
            addChild(instance);
        }

        override protected function tearDown():void {
            super.tearDown();
            removeChild(instance);
            instance = null;
        }

        public function testInstantiated():void {
            assertTrue("instance is ViewComponent", instance is ViewComponent);
        }

        public function testGoToHalfSize():void {
            instance.width = 400;
            instance.height = 200;
            instance.goToHalfSize();

            assertEquals('width', 200, instance.width);
            assertEquals('height', 100, instance.height);
        }
    }
}

Assume we have a feature that performs some asynchronous action:

package net {
    
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.utils.setTimeout;
    
    [Event(name="complete", type="flash.events.Event")]
    public class AsyncMethod extends EventDispatcher {
        
        public function doSomething():void {
            setTimeout(function():void {
                dispatchEvent(new Event(Event.COMPLETE));
            }, 100);
        }
    }
}

We can test this feature with the following test case:
package net {

    import asunit.framework.TestCase;
    import flash.events.Event;

    public class AsyncMethodTest extends TestCase {
        private var instance:AsyncMethod;

        public function AsyncMethodTest(methodName:String=null) {
            super(methodName)
        }

        override protected function setUp():void {
            super.setUp();
            instance = new AsyncMethod();
        }

        override protected function tearDown():void {
            super.tearDown();
            instance = null;
        }

        public function testInstantiated():void {
            assertTrue("instance is AsyncMethod", instance is AsyncMethod);
        }

        public function testDoSomething():void {
            instance.addEventListener(Event.COMPLETE, addAsync());
            instance.doSomething();
        }
    }
}