18
votes

I'm trying to improve my code by writing unit tests for my ActionScript 3 code for Flash projects I work on, but I'm having a mental hurdle understanding how to deal with it in the context of a Flash program. I can't seem to wrap my head around how to deal with things like addChild and the stage, as well as all the asynchronous processing typical of Flash applications (addEventListeners for waiting for things to load, etc.). Is it really any different than any other language? How does a developer deal with the unique environment of a Flash program?

A few clarifications:

  • This has nothing to do with Flex, no Flex is involved at all.
  • Programs only involve AS3 code files and an FLA containing assets.
2

2 Answers

11
votes

Great question. It's a challenge to pick what parts of a project to test - a single class or collection of classes, or both.

Although testing around the user interface testing can catch many logic and event errors, the UI is commonly where plenty of strange things can happen. Many errors in a Flash project can be due to unexpected user interaction modes - basically a beta tester does something in the UI you never would have thought of doing.

If your project is driven by user interaction, especially game oriented as opposed to RIA-oriented, planning a good set sequence of tests is as important as the tests themselves. For example, you may try action A, then action B, knowing that B depends on A because that's how you wrote it. A tester may try B before A, a scenario you may not have expected and one that would not be caught if A and B were tested independently as units. It may also mean you would want to write 3 or 4 tests: A, B, A->B, and B->A, so the number of states can get out of hand.

Something to consider is a testing framework like Flexunit to automate many of the tasks.

Edit: I should note that FlexUnit works for pure AS3 as well.

6
votes

I like abstracting application logic from front-end display stuff. I don't believe it is very useful to unit-test front-end/display stuff, but you can unit test the internal logic and functionality of the system. It's the MVC design pattern.

For example: Suppose you have a Flash game where there is a player that can attack enemies. You might have a class Player, a class Monster, and a method Player.attack(monster:Monster).

Your unit tests will set values in a Player and Monster, and call attack() and then make sure the results are correct.

Your front-end display, the stage, clickable objects, etc. and UI will also make calls to these objects when appropriate in a live environment.

The unit tests would run in a separate .swf file which executes tests that import the model objects (Player, Monster, and whatever else you might have), but completely ignore all your visual/display elements. I would avoid unit testing anything that involves user interaction.