Wednesday, October 22, 2008

Start Testing with JUnit

Little Background of Testing
In order to understand testing, Lets take a hypothetical example of a Vacation website, which will allow users to do following operations
  1. Check for deals
  2. Trip Details
Now In order to make sure the these functionality are working correctly, there are two types of testing need to be perform, they are
  • BLACK BOX Testing : Plain testing of the website, to see if all the links are working, user is able to login, logout. This is called as blackbox testing as users are not aware of the technology or code behind it, but only from the users point of view.

    Where users and QA team of the banking website will test the functionality, by actually performing the various operations supported.

  • WHITE BOX Testing : This is where the developers(you) who write the code, kick in. Its the responsibility of the developer to make sure the Java classes and methods written by him work as desired. JUNIT is a piece of software which help the developer to write and execute these tests.

The Need for JUNIT
  • From Managers Point Of View : In case of test driven development, where testcases are written first, Managers can track the progress by checking the status of number of cases that passed, failed or have an error(i.e unimplemented)
  • From Developer Point of View : For each Java class, a TestCase is written with methods that needs to be tested.
JUNIT Versions
JUNIT currently has two popular version , 3.8 and JUNIT4. Older systems use 3.8. Difference is JUNIT4 is more POJO based. JUnit 4 does not to have a prefix of testxxx before each test method.


Setup
To start having unit test from Eclipse, following steps are needed
1. Add Junit.jar to your class path
2. Click on New->Java->JUnit->TestCase
3. This automatically will create a TestCase class, here is how the TestCase class looks
import junit.framework.TestCase;

public class SampleTest extends TestCase {
public void setup() // In this method we initialize the sample Data to be passed
public void testxxx() //these are the actual methods, replace xxx with
//your method name to be tested
public void destroy() // release the sample data resources


}
4. Write the setup, testxxx and destroy methods..
5. Run the test casses, by Select the Testcase and Right click and select RunAs-->Junit Testcase

TestCase LifeCycle
Each test case has 3 phases of lifecycle
1. Setup() : In this method we initialize the sample data, which will be using for testing.
2. testxxx() : This is the actual execution cycle. Where methods are tested by comparing the sample data against the actual data
3. destroy() : release the resources.

Assert method
Each testcase extends the Junit.TestCase class, TestCase class has a Assert method, this is the main method which is used to compare the actual value recieved with the expected result,
if they dont match, an assert is generated and test case fails else it passes.