Monday, August 11, 2008

JUnit Test Case

One of the tenets of agile development is continuous testing. Agile development states that code should be tested as often as possible, during development. Not only should the new module be tested, the whole application should be tested each time a new module or new feature is added to it, to ensure that the application is not broken. In case of manual testing, if testing frequency is increased, tester moral will become very low. As the number of tests to be executed increases, testers may miss executing a few tests, resulting in problems at later stages. To overcome some of these problems, usage of automated testing in the development cycle is crucial. Though automated testing will not identify all code bugs, it will overcome the problem of low morale due to frequent execution of the tests. Usually when automated tests are executed a test log is generated. This test log is analyzed for success or failure of the tests. Such test logs can be circulated to the customer, to assure the customer that the developed code does work as expected under test conditions. Such an exchange of information will build customer’s confidence in the development team and the development process.
JUnit

JUnit, as the name suggests is an API for developing unit test cases using Java. Unit tests are used to test the business logic of the application.

Each test case is derived from the TestCase class. Each unit test starts with the prefix “test”. The success or failure of each test is determined by “assert”ing the result. If the result matches expectation, the test is a success. Else the test is a failure.

Key Points:

JUnit is open source project and hence it is free !!
Fast development while increasing quality of code.
Easy to understand.
Integrated with IDE’s like Eclipse and Ant, makes it easy to use and inexpensive to write.
Provides immediate feedback about code changes.
Regression testing can be automated using Junit test suites.
Increases stability of software.
Without going into the much details, lets have a look how the junit test cases are prepared in real case:

Writing Sample TestCase:

Test Class:
public class Demo {
static public int add(int a, int b) {
return a + b;
}
}

JUNIT TestCase

import junit.framework.*;
public class DemoTest extends TestCase {
setUp() { }
tearDown() { }
public void testAdd() {
int no1 = 5;
int no2 = 5;
int total = 10;
int addResult = 0;
addResult = Math.add(no1, no2);
assertEquals(total,addResult);
}
}


JUnit TestSuite:

JUnit TestSuite includes several test cases. It allows multiple test cases to run in one go. It also automates regression testing process.

To write a test suite, follow these steps:
ü Write a Java class that defines a static suite() factory method that creates a TestSuite containing all the tests.
ü Optionally define a main() method that runs the TestSuite in batch mode.


public class JUnitPracSuite {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite("Test for Demo");
suite.addTestSuite(Demo.class);
//More TestCase classes to be added.
return suite;
}
}


Running a TestSuite will automatically run all of its subordinate TestCase instances and TestSuite instances. Running a TestCase will automatically invoke all of its public testXXX() methods. JUnit provides both a textual and a graphical user interface. The interface provided are No. of Test cases Run, Simple sompletion status, Error if any.

To run textual user interface----java junit.textui.TestRunner MathsClassTest
To run graphical user interface----java junit.swingui.TestRunner MathsClassTest
To run TestSuite----java junit.swingui.TestRunner JUnitPractSuite

TestCase object extends Assert which provides way to judge if a test has succeeded or failed:

Types of Assert statements:
assertEquals: Provides a series of overloads that allows to test if an actual value matches the expected one.
assertFalse: Use this if the function will always return false (fails if it receives true)
assertNotNull: If method returns null in the event of failure use this to check to see if it succeeds.
assertNotSame: If method is supposed to return an element from a list, use this to check if the element returned is the one from the actual list
assertNull: If method returns null in the event of failure, use this to check to see if it fails
fail: Will fail the test, use this in conjunction with conditionals
failNotEquals: Essentially the same as assertEquals but will fail the test if they aren’t equal instead of causing an error
failNotSame: Essentially the same as assertNotSame except instead of causing an error it will cause a failure

Suggestions for arranging tests in development environment:

Create test cases in the same package as the code under test.
To avoid combining application and testing code in your source directories, create a mirrored directory structure aligned with the package structure that contains the test code.
For each Java package in your application, define a TestSuite class that contains all the tests for validating the code in the package.
Define similar TestSuite classes that create higher-level and lower-level test suites in the other packages (and sub-packages) of the application.
Make sure your build process includes the compilation of all tests.


To Watch:

The software does well those things that the tests check.
Test a little, code a little, test a little, code a little...
Make sure all tests always run at 100%.
Write tests for the areas of code with the highest probability of breakage.
Write tests that have the highest possible return on your testing investment.
If you find yourself debugging using System.out.println(), write a test to automatically check the result instead.
Write unit tests before writing the code and only write new code when a test is failing.

Download JUnit latest version from http://www.junit.org/home
Hope you all will find it useful.

No comments:

Total Pageviews