A First Date with Unit Testing in Flash Builder 4

-

Tuesday, September 15th, 2009

Unit testing is a topic that creates a variety of opinions. For a lot of people it is like a first date – the first time they try to take out unit testing for a spin it seems like it is fat, slow, and impedes what you want to get done. For others, it is love at first sight.

To be honest, I still struggle to decide if I want to include unit testing in my relationship with each new project I take on. I know that it is needed, and that it really is best practice, but then I get thoughts such as:

  • “Is unit testing critical to this mission?”
  • “This is just a small project, it really doesn’t need it”
  • “Crap, I don’t like Test Driven Development”

Even though I murmur about the different times to use unit testing, as Flex and Flash keep moving to become bigger players in developing true business applications,  the greater the need to verify an applications functionality.

What’s cool about Flash Builder 4 and unit testing is that we finally have a solution that is actually built into the IDE. It seems that the wars between FlexUnit, FlexMonkey, Structured Log Testing, and AsUnit were won by Flex Unit when they were crowned by Adobe to be integrated in the IDE.

If you need a refresher in what unit tests are and why they are important, check this out.

So let’s take a first date with unit tests in Flash Builder 4.

1) Create a project and create a simple class that will do some business logic we want to test. In this example, we use the standard bank account example that makes deposits and withdrawals.
package
{
public class Bank
{
public function Bank() { }

private var _balance:Number;

public function get balance():Number {
return _balance;
}

public function set balance(v:Number):void {
_balance = v;
}

/**
* Deposit some money into our bank
* @param ammount
* @return
*
*/
public function deposit(ammount:Number):Number {
_balance += ammount;
return balance;
}

/**
* Withdraw some money from our bank
* @param ammount
* @return
*
*/
public function withdraw(ammount:Number):Number {
_balance -= ammount;
return balance;
}
}
}

2) Now it’s really easy to create a test case. Just right click the class you want to test and create a new test case off it:

newTestCase

This will name the class what it should be called (in our case BankTest.as) and insert all of your stub functions to setup/tear down the test case. You will also notice one extra file created in your directory called FlexUnitCompilerApplication. This exists simply to be the application that runs when you execute the test cases. It will also show you a nice pretty dialogue when all your tests run successfully.

3) Configure your test case. Below is a sample:
package flexUnitTests
{
import flexunit.framework.TestCase;

public class BankTest extends TestCase
{
// please note that all test methods should start with 'test' and should be public

// Reference declaration for class to test
private var classToTestRef : Bank;

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

//This method will be called before every test function
override public function setUp():void
{
super.setUp();
classToTestRef = new Bank();
}

//This method will be called after every test function
override public function tearDown():void
{
super.tearDown();
}

/* sample test method
public function testSampleMethod():void
{
// Add your test logic here
fail("Test method Not yet implemented");
}
*/

/**
* Do a test deposit
*
*/
public function testDesposit():void {

//Reset our balance to zero
classToTestRef.balance = 0;

//An ammount to deposit
var ammount:Number = 1000;

//Deposit the ammount
classToTestRef.deposit(ammount)

//Check to make sure that this deposit posts to the balance successfully
assertEquals(ammount, ammount);
}

/**
* Do a test on a withdrawal
*
*/
public function testWithdrawal():void {

//Reset our balance to zero
classToTestRef.balance = 1000;

//An ammount to withdraw
var ammount:Number = 400;

//What the end ammount of our withdrawal should be
var endAmmount:Number = 600;

//Withdraw the ammount
classToTestRef.withdraw(ammount);

//Check to make sure that this withdrawal posts to the balance successfully
assertEquals(endAmmount, endAmmount);
}
}
}

Now just run your test! See, it’s that easy!

executeTests

If you are successful, you will see two screens with the results of your tests. The first will be in the browser, but the most useful one will be right inside your IDE where you can see which tests executed successfully and which ones did not.

ideTest

So there you go. That was a nice, easy first date with unit tests in Flash Builder 4!

Download the source files.

Flex: Loading Remote Modules Throws the following: “Error: Unable to load resource module from…”

-

Friday, August 7th, 2009

Recently I was working on localizing a Flex project to handle mutliple languages.  There are a bajilion examples on the web of ways to do this, and I found a few helpful ones.  The most helpful was this one.

Since the strings are changed by the client in a php admin console, the server was compiling these modules for each language I needed.  So, the Flex app had to load the resource modules at run time, AND they were coming from a different domain (S3 in our case).  I played with the security settings for loading a remote module as suggested by sites like this: And I was able to get my app to load the resource module from an external domain when I ran the Flex app from localhost, but when I tried to run the app locally, I kept getting this error:

“Error: Unable to load resource module from http://domainname.com/locales/en_US.swf”

I didn’t want to always debug my app from localhost, (thats lame) so I needed a way around the Flex security restrictions.

I dug around a while looking for something to get my by, and I found people with the same error here and here. Along with one result in Russian, which I didn’t understand.  Generally the answer was to load things from localhost and that should solve your issue, but like I said didn’t want to run things from localhost.

Then a beam of light crested over the horizon, licking the hopless feelings which had me on the verge of desisting. I asked coworker, and fellow Flexer Aaron Hardy what he recommended, and he pointed me to something he had done for loading style modules.  He said: “Try this. It might work” So I gave it a whirl, and BAM! It worked first try baby.  So here is what I had:

private function loadLocaleResource():void
{
var eventDispatcher:IEventDispatcher =
resourceManager.loadResourceModule("FULL_URL_TO_MODULE");
eventDispatcher.addEventListener(
ResourceEvent.COMPLETE, resourceCompleteHandleer);
}

and after getting the RemoteStyleMarshaller from Aaron, this is what I changed it to:

private var moduleLoader:RemoteStyleMarshaller;
//loads the module with the locale resources
private function loadLocaleResource():void
{
moduleLoader = new RemoteStyleMarshaller("FULL_URL_TO_MODULE", false);
moduleLoader.addEventListener(StyleEvent.COMPLETE, resourceCompleteHandleer);
moduleLoader.loadStyleDeclarations();
}

You can find a full explanation of what Aaron’s class does at his blog. Basically what his RemoteStyleMarshaller does is skirt around the security settings of Flash by loading in the bytes of the module.

Hopefully this post, along with Aaron’s class will help anyone running into the same issue.

NOTE:  After working through this issue with Aaron, he may post an update to his code on his site, since now it is apparent that his RemoteStyleMarshaller does more than just marshall style modules. Aaron is the hero of the day.

iPhone HTTP Connection Debugging

-

Tuesday, August 4th, 2009

Nearly all iPhone applications take advantage of the device’s amazing internet connectivity. Whether its checking the balance of your bank account or using an interactive web application in Safari, there is a tangible level of connectedness. Wouldn’t it be great if you could watch, log, and edit the HTTP requests live as they happen from the comfort of your desktop? Not only is it possible, it is easier than you might think and doesn’t require jailbreaking your device! This article shows you how in just a few easy steps.

<soapbox>

May I take this opportunity to offer my highest recommendation for a wonderful piece of software called the Charles debugging proxy. The software allows you to view and edit HTTP requests that filter through its proxy server. It is secure, easy to install and configure, and runs on both Windows and OS X. Charles has become an essential tool in my web developer bag of tricks and I use it everyday.

You can download a free trial, but you won’t regret purchasing a license for only US $50.

http://www.charlesproxy.com

</soapbox>

This tutorial will focus on connecting iPhone applications with the Charles debugger

Prerequisites

  • A wireless LAN subnet to which your iPhone has access and is connected
  • A laptop or desktop machine on the same LAN subnet as your iPhone
  • Charles debugging proxy installed

There are two main areas of setup, the Charles proxy host, and the iPhone device.

Part 1 – Charles Proxy Host Setup

  1. Run Charles and verify that you have sufficiently enabled access through your system’s local firewall. Often this simply involves disabling the software firewall on your operating system. Charles needs to be listening on your LAN IP address and its default port is 8888. See your Operating System’s documentation for this specific procedure.
  2. Note your system’s IP address. In my case it is 10.45.200.127

Part 2 – iPhone Setup

  1. Download the charles SSL intermediate certificate

    http://www.charlesproxy.com/charles_ca_certificate.zip

  2. Extract the charles.cer file from the zip archive.

    At this point you have two ways you can install the charles.cer file on your device. You can either email it to yourself and open the attachment from the device. Or, you can post the file on a web server and request the certificate in Safari on the device. Either method will raise an Install prompt that looks like the one below:

    Charles Certificate Install

  3. Configure your iPhone to use a proxy server

    This step involves going to the Settings application and into the Wi-Fi section. There you will hopefully see an option for the Wireless AP name you are connected to.

    Go to: Settings -> Wi-Fi -> “Your Wireless AP Name”

    Once there, scroll to the bottom of the window and you should see settings options to configure a proxy host as below:

    Proxy Config

    Enter your Charles proxy host address and port in the inputs provided

    NOTE: Once you are done using the Proxy, you will have to set your HTTP Proxy setting to “Off” for your phone to return to normal function.

  4. Test the configuration

    Open Safari and visit a website. You should see a prompt on your Charles machine to authorize the connection (this keeps unauthorized users from using your Proxy server):

    Charles Authorization

    Once the connection has been authorized, voilá! You should now see your phone’s HTTP requests live in Charles. For even more detail, you can click on the “Sequence” view.

Several useful things you can do with Charles at this point:

  1. Save file requests to disk by right clicking and choosing “Save Response…”
  2. Edit and resend HTTP requests by clicking the “Edit” icon on the toolbar with a request selected
  3. Debug SSL connections
  4. Throttle and simulate 3G network speeds in order to view how your app may respond. See “Throttle Settings” under the Proxy menu option.

Charles Preview

Take a look at the Charles Documentation for other tips and tricks:

http://www.charlesproxy.com/documentation/using-charles/

Enjoy, and happy hacking!!