Dependency Injection in Flex Applications – Spring ActionScript and Cairngorm

After layering many new features into our applications we see complexity emerge, and as complexity emerges we need to find techniques to keep our objects clean and testable. Complexity, as we looked at earlier, is a major challenge for large applications. Object complexity is increased as object collaboration increases; the more collaboration, the more complexity. This is complexity not only in objects performing their work, doing what they were designed to do, but also in testing.

We looked to some approaches in Unit Testing to help keep Command complexity under control and give our applications more robust testing coverage. Now we are going to upgrade these approach with some discussion and refactoring based on Dependency Injection.

Dependency Injection in a Nutshell
Eric Feminella has a great post on this that is worth reading.  Dependency Injection basically describes separating configuration from implementation. Swapping in and out different object dependencies in different application contexts hasn’t been implemented very cleanly in traditional Object Orientated languages.  In light of this, frameworks like the Spring Framework have risen in popularity over the last few years.

Christophe Herreman and Spring ActionScript

Many thanks to Christophe Herreman for releasing “Spring ActionScript” (formerly known as Prana) a Spring-like IoC container for Actionscript 3.  The project has been out for a while and has already gone through a few iterations.  Christophe has updated the Cairngorm Application Blueprint (the Cairngorm Store) with a Spring ActionScript Enabled version.  We will draw upon these ideas in Spring ActionScript-enabling an example application from a previous post.

Injecting Command Dependencies

Rather than declaring our two Command dependencies (the Model and a Delegate) as internal fields that unit tests in the same package can override (inject) with their Mocks, we will let Spring ActionScript do that work for us.  This results in a cleaner implementation where the Commands are completely de-coupled from our form of injection.

Let’s take a look at the refactoring:

UpdatePreferencesCommand.as (Before)

package com.allenmanning.exampleflexapp.account.commands {

    import com.adobe.cairngorm.commands.Command;
    import com.adobe.cairngorm.control.CairngormEvent;
    import com.allenmanning.exampleflexapp.account.business.IAccountDelegate;
    import com.allenmanning.exampleflexapp.account.event.UpdatePreferencesEvent;

    import mx.rpc.IResponder;

    /**
     * Command that updates application UserPreferences for a particular User- collaborates with
     * the Account Delegate for persistence, and updates the local Account Model
     *
     * @author amanning
     */
    public class UpdatePreferencesCommand implements Command, IResponder {

        //------------------------------------------------------------------------------------------
        // Member variables
        //------------------------------------------------------------------------------------------
        /** The remote account management proxy */
        internal var _accountDelegate:IAccountDelegate;

        //------------------------------------------------------------------------------------------
        // Constructors
        //------------------------------------------------------------------------------------------
        /**
         * Class constructor, initialize collaborators
         */
        public function UpdatePreferencesCommand():void {

            //once the account delegate has been created we will initialize it it here
            // _accountDelegate = new AccountDelegate(this);

        } 

        //------------------------------------------------------------------------------------------
        // Methods
        //------------------------------------------------------------------------------------------
        /**
         * Execute this command - update the Preferences and wait for response
         *
         * @param cairngormEvent    the CairngormEvent which was dispatched to invoke this command
         */
        public function execute(cairngormEvent:CairngormEvent):void {

            var event:UpdatePreferencesEvent = (cairngormEvent as UpdatePreferencesEvent);

            // Consider using an Assert?
            if(event.user == null || event.userPreferences == null) {
                throw new Error("Invalid event data");
            }

            _accountDelegate.updatePreferences(event.user.id, event.userPreferences);

        }

        /**
         * Event listner for the successful result from the delegate- update the local model with
         * the results
         *
         * @param data   The data passed back from the server.  While <code>data</code> is typed as
         *               Object, it is often (but not always) an mx.rpc.events.ResultEvent.
         * @see          mx.rpc.IResponder#result
         */
        public function result(data:Object):void {

        }

        /**
         * Event listener for the error result from the delegate- log the error
         *
         * @param info   The application fault.  While <code>info</code> is typed as Object it is
         * often (but not always) an mx.rpc.events.FaultEvent.
         *
         */
        public function fault(info:Object):void {

        }

    }

}

UpdatePreferencesCommand.as (After, using Spring ActionScript)

package com.allenmanning.exampleflexapp.account.commands {

    import com.adobe.cairngorm.commands.Command;
    import com.adobe.cairngorm.control.CairngormEvent;
    import com.allenmanning.exampleflexapp.account.business.DelegateLocator;
    import com.allenmanning.exampleflexapp.account.business.IAccountDelegate;
    import com.allenmanning.exampleflexapp.account.event.UpdatePreferencesEvent;
    import com.allenmanning.exampleflexapp.account.model.IAccountModels;
    import com.allenmanning.exampleflexapp.account.model.UserPreferences;
    import com.allenmanning.exampleflexapp.error.Assert;
    import com.allenmanning.exampleflexapp.model.ModelLocator;

    import mx.rpc.IResponder;
    import mx.rpc.events.ResultEvent;

    /**
     * Command that updates application UserPreferences for a particular User- collaborates with
     * the Account Delegate for persistence, and updates the local Account Model
     *
     * @author amanning
     */
    public class UpdatePreferencesCommand implements Command, IResponder {

        //------------------------------------------------------------------------------------------
        // Methods
        //------------------------------------------------------------------------------------------
        /**
         * Execute this command - update the Preferences and wait for response
         *
         * @param cairngormEvent    the CairngormEvent which was dispatched to invoke this command
         */
        public function execute(cairngormEvent:CairngormEvent):void {

            Assert.isTrue(
                ModelLocator.getInstance().accountModels.userIsLoggedIn,
                "The user must be logged in");

            var event:UpdatePreferencesEvent = (cairngormEvent as UpdatePreferencesEvent);

            Assert.notNull(event.user, "The user must not be null");
            Assert.notNull(event.userPreferences, "The preferences must not be null");

            var delegate:IAccountDelegate = DelegateLocator.getInstance().accountDelegate;

            delegate.updatePreferences(event.user.id, event.userPreferences);

        }

        /**
         * Event listener for the successful result from the delegate- update the local model with
         * the results
         *
         * @param data   The data passed back from the server.  While <code>data</code> is typed as
         *               Object, it is often (but not always) an mx.rpc.events.ResultEvent.
         * @see          mx.rpc.IResponder#result
         */
        public function result(data:Object):void {

            var updatedPreferences:UserPreferences =
                ((data as ResultEvent).result as UserPreferences);

            Assert.notNull(updatedPreferences, "The preferences must not be null");

            ModelLocator.getInstance().accountModels.preferences = updatedPreferences;                    

        }

        /**
         * Event listener for the error result from the delegate- log the error
         *
         * @param info   The application fault.  While <code>info</code> is typed as Object it is
         * often (but not always) an mx.rpc.events.FaultEvent.
         *
         */
        public function fault(info:Object):void {
            // TODO implement this
        }

    }

}

There are two major differences in the above refactorings.
_accountDelegate has been removed. We were using an internal variable to inject the delegate into this class before. We would inject a mock for our unit tests after the object has been constructed. We have replaced this with a new DelegateLocator.

In the Prana Store example, the delegates were injected onto the Model Locator. This tight coupling between the business model and the delegates is something we should move away from. Delegates and Models should have now knowledge of each other.

The second major difference that we have added a basic implementation for the onResult function- the results are being set into the model. This is another area that we are using dependency injection. Both the accountDelegate and the accountModel are being injected using Spring ActionScript. The command itself is gaining access to these dependencies through two Singleton Locator Objects.

Injecting The Dependencies
In our application-context.xml we wire up the relationships. In this case, we are using mocks for testing. The DelegateLocator has a mock account delegate injected into it. The same goes for the Account Model in the ModelLocator. In both cases we are injecting Mocks for testing purposes. For a deployment context, the application-context.xml would be different.

application-context.xml

<objects xmlns="http://www.pranaframework.org/objects"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.pranaframework.org/objects http://www.pranaframework.org/schema/objects/prana-objects-0.6.xsd">

	<!-- =================================================================== -->
	<!-- This application context defines a single test configuration, it can be expanded to include
	       a deployment configuration as well, please see comments below.
		 
		 1. Testing: Mock Delegates
		 2. Deployment: Remote Object Delegates
		 
		 To use a configuration, uncomment it and comment the one you don't
		 want to use. By default, the Mock Delegates configuration is used.

	-->
	<!-- =================================================================== -->

	<!-- =================================================================== -->
	<!-- 1. Testing: Mock Delegates -->
	<!-- =================================================================== -->
	<object id="DelegateLocator" 
	       class="com.allenmanning.exampleflexapp.account.business.DelegateLocator" 
	       factory-method="getInstance">

        <property name="accountDelegate">
            <object class="com.allenmanning.exampleflexapp.account.business.MockAccountDelegate"/>
        </property>

	
	</object>

    <object id="ModelLocator" 
           class="com.allenmanning.exampleflexapp.model.ModelLocator" 
           factory-method="getInstance">

        <property name="accountModels">
            <object class="com.allenmanning.exampleflexapp.account.model.MockAccountModels"/>
        </property>

    </object>
	
	<!-- =================================================================== -->
	<!-- 2. Deployment: Remote Object Delegates -->
	<!-- =================================================================== -->
    <!--
    <object
           id="DelegateLocator" 
           class="com.allenmanning.exampleflexapp.account.business.DelegateLocator" 
           factory-method="getInstance">

            <property name="accountDelegate">
	            <object class="TODO create real account delegate"/>
	        </property>
    


    <object id="ModelLocator" 
           class="com.allenmanning.exampleflexapp.model.ModelLocator" 
           factory-method="getInstance">
  
        <property name="accountModels">
            <object class="com.allenmanning.exampleflexapp.account.model.AccountModels"/>
        </property>

    </object>
    -->
</objects>

Testing with Mocks and Spring ActionScript Our unit test for this command, assumes that Mocks have been injected into our Command and take advantage of these to test the object behavior.

package com.allenmanning.exampleflexapp.account.commands {

    import com.allenmanning.exampleflexapp.account.business.DelegateLocator;
    import com.allenmanning.exampleflexapp.account.business.IAccountDelegate;
    import com.allenmanning.exampleflexapp.account.business.MockAccountDelegate;
    import com.allenmanning.exampleflexapp.account.event.UpdatePreferencesEvent;
    import com.allenmanning.exampleflexapp.account.model.IAccountModels;
    import com.allenmanning.exampleflexapp.account.model.MockAccountModels;
    import com.allenmanning.exampleflexapp.account.model.User;
    import com.allenmanning.exampleflexapp.account.model.UserPreferences;
    import com.allenmanning.exampleflexapp.error.AssertionError;
    import com.allenmanning.exampleflexapp.model.ModelLocator;
    import com.anywebcam.mock.Mock;

    import flexunit.framework.TestCase;

    import mx.rpc.events.ResultEvent;

    /**
     * Responsible for testing the Command that updates application UserPreferences for a
     * particular User
     *
     * @author   amanning
     */
     public class UpdatePreferencesCommandTest extends TestCase {

        //------------------------------------------------------------------------------------------
        // Member Variables
        //------------------------------------------------------------------------------------------
        /** The command that we are testing */
        private var _commandToTest:UpdatePreferencesCommand;

        /** A fake user, used in testing */
        private var _fakeUser:User = new User(123456, 'aFakeUser');

        /** Fake user preferences, used in testing */
        private var _fakePreferences:UserPreferences = new UserPreferences(false);            

        /** A fake event used in testing */
        private var _fakeEvent:UpdatePreferencesEvent =
            new UpdatePreferencesEvent(_fakePreferences, _fakeUser);

        /**
         * A mock Account delegate, with configurable expectations - used in testing.  We have
         * injected this mock into the Delegate locator.
         */
        private var _mockAccountDelegate:IAccountDelegate =
            DelegateLocator.getInstance().accountDelegate;

        //------------------------------------------------------------------------------------------
        // Constructors
        //------------------------------------------------------------------------------------------
        /**
         * Class Constructor
         *
         * @param methodName    the test to add to this test suite
         * @see                 flexunit.framework.TestCase
         */
        public function UpdatePreferencesCommandTest( methodName:String = null ) {

            super( methodName );

        }

        //------------------------------------------------------------------------------------------
        // Methods
        //------------------------------------------------------------------------------------------
        /**
         * Called before every test to create testing data, or reset any test-specific properties
         *
         * @see    flexunit.framework.TestCase#setUp
         */
        override public function setUp():void {

            _commandToTest = new UpdatePreferencesCommand();
            (_mockAccountDelegate as MockAccountDelegate).mock = new Mock();

            var accountModel:IAccountModels = ModelLocator.getInstance().accountModels;
            (accountModel as MockAccountModels).mock = new Mock();

        }

        /**
         * Called before after test to clean up testing data
         *
         * @see    flexunit.framework.TestCase#tearDown
         */
        override public function tearDown():void {

            // if this mock was not interacted with, and we expected it to this should throw an
            // exception
            (_mockAccountDelegate as MockAccountDelegate).mock.verify();
            (ModelLocator.getInstance().accountModels as MockAccountModels).mock.verify();

        }

        public function testUserNotLoggedIn():void {

            var accountModel:IAccountModels = ModelLocator.getInstance().accountModels;
            (accountModel as MockAccountModels).mock.property("userIsLoggedIn").returns(false);

            try {

                _commandToTest.execute(_fakeEvent);

            } catch (error:AssertionError) {

                // expected
                return;

            }

            fail('An Assertion Failed Error should have been thrown');

        }

        /**
         * Testing utility function for executing the command with invalid data, execute should
         * throw an exception
         *
         * @param invalidFakeEvent  a fake event with invalid data
         *
         */
        private function invalidDataTester(invalidFakeEvent:UpdatePreferencesEvent):void {

            try {

                _commandToTest.execute(invalidFakeEvent);

            } catch(e:Error) {

                if(e.message.indexOf("No Expectation set for updatePreferences with args") != -1) {

                    fail("updatePreferences should not be called with invalid data");

                } else {
                    // It was expected to fail
                    return;
                }

            }

            fail("An exception was expected, the event was not properly populated");

        }

        public function testExecuteNullDataBoth():void {

            invalidDataTester(new UpdatePreferencesEvent(null,null));            

        }

        public function testExecuteNullDataUser():void {

            invalidDataTester(new UpdatePreferencesEvent(_fakePreferences,null));            

        }

        public function testExecuteNullDataPreferences():void {

            invalidDataTester(new UpdatePreferencesEvent(null, _fakeUser));            

        }

        public function testExecute():void {

            //Configure a mock delegate and assign expectations.  We are expecting the Delegate's
            //updatePreferences method to be called only once with the correct arguments
            (_mockAccountDelegate as MockAccountDelegate).mock.method(
                    "updatePreferences").once.withArgs(
                        Number,
                        UserPreferences);

            var accountModel:IAccountModels = ModelLocator.getInstance().accountModels;
            (accountModel as MockAccountModels).mock.property("userIsLoggedIn").returns(true);

            // The mock will throw an exception, if it's "updatePreferences" method isn't called
            // exactly once with a Number and UserPreferences type arguments.
            _commandToTest.execute(_fakeEvent);

        }

        public function testOnResult():void {

            var accountModel:IAccountModels = ModelLocator.getInstance().accountModels;
            (accountModel as MockAccountModels).mock.property(
                "preferences").withArgs(UserPreferences);

            var stubbedResultEvent:ResultEvent = new ResultEvent(
                "result",
                false,
                true,
                _fakePreferences);
            _commandToTest.result(stubbedResultEvent);

        }

    }

}

There is no injection done in the test itself. The test assumes mocks have been injected into Command and we can set up expectations for how the command should interact with these mocks in different contexts.

This Flex Project includes all of the sample code run in a FlexUnit test suite.