Unit Testing with FlexUnit
Before Reading this documentation. Its been a simple effort by me to share the information whatever i have with all of the world through internet. So whatever written is all what i had understood from the FlexUnit Framework it may have some mistakes so sorry for those. But Please do inform me if you find something wrong with it ,so that this can be of great help to everybody who navigates to this page.
This is the First big document which i have made and published so Please do comment if you think you can help me or give me a some suggestions.
Thanks in Advance.
Some Definitions
- Code coverage : Code coverage is a measure used in software testing. It describes the degree to which the source code of a program has been tested. It is a form of testing that inspects the code directly and is therefore a form of white box testing (Testing done only on internal specification).
- Test harness or automated test framework : It is a collection of software and test data configured to test a program unit by running it under varying conditions and monitoring its behavior and outputs.
The typical objectives of a test harness are to:
Ø Automate the testing process.
Ø Execute test suites of test cases.
Ø Generate associated test reports.
A test harness typically provides the following benefits:
Ø Increased productivity due to automation of the testing process.
Ø Increased probability that regression testing will occur.
Ø Increased quality of software components and application.
- Regression : Regressions occur whenever software functionality that was previously working correctly stops working as intended. Typically regressions occur as an unintended consequence of program changes.
- Test Case : A test case in software engineering is a set of conditions or variables under which a tester will determine whether a application meets specifications. Test cases are often referred to as test scripts, particularly when written. Written test cases are usually collected into test suites.
- Test Oracle : The mechanism for determining whether a software program or system has passed or failed a test . In some settings an oracle could be a use case or Requirement. It may take many test cases to determine that a software program or system is functioning correctly.
- Mock objects : mock objects are simulated objects that mimic the behavior of real objects in controlled ways. In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test.
- Feature creep : It is the proliferation of features in a product where extra features go beyond the basic function of the product and so can result in over-complication rather than simple, elegant design.
Unit testing
What is Unit and Unit testing?
- Unit testing is a method of testing that verifies the individual units of source code are working properly. A unit is the smallest testable part of an application. In Flex, this means a function, or more appropriately a method as Flex/ActionScript is an object oriented language.
- Unlike many other forms of software testing, unit tests are usually completed by the developer.
- The developer tests code at a low level to make sure each method is performing as expected. In theory, if each function is working properly at a low level then the higher levels of integrtion testing should have fewer errors.
Why ?
To ensures that new additions or changes to a project do not introduce bugs or modify expected behavior.
- To enables large teams to work in tandem without introducing bugs and confirm that small individual parts of a program, down to specific methods, all return the expected results.
When ?
Before writing a code for any functionality we should pass a unit test for every functionality.
Reasons for Unit Testing
- Tests Reduce Bugs in New Features
- Tests Are Good Documentation
- Tests Reduce the Cost of Change
- Tests Improve Design
- Tests Allow Refactoring
- Tests Defend Against Other Programmers to make unwanted changes
- Testing Forces You to Slow Down and Think which gives clean and simple design
- Tests Reduce Fear of worrying about breaking existing code as you add new features.
FlexUnit
“FlexUnit is an open source framework created by Adobe for unit testing in Flex”
The FlexUnit Framework allows you to create test cases and synchronous tests and evaluate test suites in a test harness application that provides a visual display of all the tests in that test suite.
The visual display has a very clear Representation for
- Number of Tests Run, Time Taken to Run Tests, Average assertions made per Test, Number of Errors, Failures and so on
- It has Filter Option for results and Search functionality
- Table View representation where we can check Result, Assrtion , expected and Actual
We can Handle Events and Test Visual Components with FlexUnit
How to include FlexUnit ?
FlexUnit is available for download on Google Code at http://code.google.com/p/as3flexunitlib/.After you extract the file from the zip, you will find a flexunit.swc in the bin directory. You need to add this library to your project
Important API
- TestRunnerBase() : TestRunnerBase is the default graphical test runner included with the FlexUnit Framework.
Property : test ( To Add the Suite ) , startTest and
Event : TestCompleteEvent
- TestSuite : TestSuite to hold the collection of tests to be run.
Property : addTest , testCount(): getTestMethodNames():
- TestCase –It defines the fixture in which to run multiple tests it inherits Assert class which provides all types of assertions(Assuptions).
Assertion Types
- assertEquals – Asserts that 2 values are equal.
- assertFalse – Asserts that a condition is false The first argument can be the message when the assertion fails.
- assertMatch – Asserts that a string matches a regexp.
- assertNoMatch – Asserts that a string doesn’t match a regexp.
- assertNotNull – Asserts that an object is not null.
- assertNotUndefined – Asserts that an object is not undefined.
- assertNull – Asserts that an object is null.
- assertStrictlyEquals – Asserts that two objects are strickly identical The first argument can be the message when the assertion fails Assert
- assertTrue – Asserts that a condition is true The first argument can be the message when the assertion fails Assert
- assertUndefined – Asserts that an object is undefined.
Steps in Writing the TestCases
- Write a single test
- Implement just enough code to get the test to compile
- Run the test and see it fail
- Implement just enough code to get the test to pass
- Run the test and see it pass
- Refactor for clarity
- Repeat
Unit Testing Example
Problem :We have to make functionality of checking an opening Balance for Account. If Account is of Type saving , then the Opening balance will be 1000 and if it is of type Current Account then opening balance is 5000.
FlexUnit is available for download on Google Code at http://code.google.com/p/as3flexunitlib/. After you extract the file from the zip, you will find a flexunit.swc in the bin directory.
Now lets start a TDD process
- Create a project say TDD
- flexunit.swc add this library to your project
- In src Create Two Folders as testCases and utils
- Our Application level file will be TDD .mxml
Step 1 :
In TDD.mxml Create an Object of TestRunnerBase Class Give it name as “testRunner” Code will look like this
<flexunit:TestRunnerBase width=”100%” height=”100%” />
Write Two Function as
//Assigns a testSuite to the TestRunnerBase which we will start executing
//Called from CreationComplete Event of Application
private function onCreationComplete():void
{
testRunner.test = createSuite();
testRunner.startTest();
}
private function createSuite():TestSuite{
var testSuite:TestSuite = new TestSuite();
return testSuite;
}
Step 2 :
Create a class AccountManagerTest Extends TestCase within the package testCases.Write a method “testOpeningBalance” where We will write a test cases for
/**
* Account types are
* s – Saving Account with minBalance = 500;
* c – Current Account with minBalance = 1000;
*
*/
public function testOpeningBalance():void
{
}
Step 3 :
Create a class AccountManager.
Write a two methods
openAccount() – It will create a account with given type with required respective opening balance.
getMinBalance() – It will return the balance of the particular Instance which we will test in our test case method testOpeningBalance method of AccountManagerTest.
The Code should look like :
private var balance:int = 0;
private var _type:String;
public function openAccount(type:String):void
{
_type = type.toLowerCase();
}
public function getMinBalance():Number{
return balance;
}
Step 4 :
Add the Tests to the testOpeningBalance method of AccountManagerTest class as
public function testOpeningBalance():void
{
var validatedeposite:AccountManager = new AccountManager();
validatedeposite.openAccount(“S”);
assertEquals(“Balance after Opening Saving Account is 1000″, 1000, validatedeposite.getMinBalance());
validatedeposite.openAccount(“C”);
assertEquals(“Balance after Opening Current Account is 5000″, 5000, validatedeposite.getMinBalance());
}
Now Run The Project see that the Test Case Fails
Step 5 :
Now implement just enough code so that the testCase Passes.
For this rewrite the method openAccount() in AccountManager class so that the testCase passes.
The Code looks like this,
public function openAccount(type:String):void
{
_type = type.toLowerCase();
if(_type==’s’)
{
balance = 1000;
}else if(_type==‘c’)
{
balance = 5000;
}
}
Run the Project again Test Case Passes
Now I guess You are Rocking with Flex Unit Hurrey.
Download Links are As Follows
flexUnit Sample Application zipped and renamed
(Download the file and rename .doc by .zip)
All Flex Unit Resources can be found at
http://opensource.adobe.com/wiki/display/flexunit/Developer+Documentation
Say Cheese
Thanks and regards
Shashank Kulkarni.
Feel free to comment on the post ![]()
Recent Comments