View RSS Feed

My Java Tips

An Introduction To JUnit

Rate this Entry
by , 11-08-2011 at 07:51 PM (1185 Views)
In a big project programmer needs to test his code as a unit, Separately from other part of project. So there was a need of some framework which can provide testing for implementing testing in Java.

JUnit provides a simple way to explicitly test specific areas of a Java program. It can be used to test a hierarchy of program code either as individual or as multiple units. Using JUnit framework is beneficial because it forces us to explicitly declare the expected results of specific program execution. While debugging the program, It is possible to write a test which asserts that the expected result is same as the resultant or the evaluated value in the program. This is widely used in Test Driven Development (TDD) which is simply a three step process - write test, write code, re-factor code. By TDD you will first write the tests then write the functional code to make the tests run. You will continue writing test on the point that changing any functional code will break some tests.

JUnit supports the idea of first testing then coding. TDD improves stability of program code while reducing programmer stress and the time spent in debugging program. Many Java IDE like Eclipse, NetBeans provides support for creating ,running and debugging JUnit Test cases but usually it is integrated with Ant. Latest verions of Eclipse comes with the built in Junit library. The editor provides a seamless integration with Junit.

Here are the tips for installation of JUnit Framework.



Download the latest version of JUnit from http://download.sourceforge.net/junit/
Uncompress the zip to a directory at your local drive say c :\somefolder;
Add c:\some folder/junit/junit.jar to your Java CLASSPATH environment variable.

Now JUnit is configured and you can work with JUnit.

Now we can go with basic programs of JUnit.
Java Code:
    import junit.framework.*;public class SimpleCalculationTest extends TestCase {

    public SimpleCalculationTest(String name) {

    super(name);

    }

    public void testSimpleTest() {

    int answer = 2;

    assertEquals((1 + 1), answer);

    }

    }
Goto the the command prompt compile the program and run it.

C:\rootfolderOfJavaClass java junit.textui.TestRunner SimpleCalculationTest

It will give the output.


Time: 0OK (1 tests)

Other then “ assertEquals ” methods there are a lot of methods available in Junit Framework like “ assertNOtNull ”, “ assertTrue ”, “ assertFalse ” that can be used as per programming need.

Submit "An Introduction To JUnit" to Facebook Submit "An Introduction To JUnit" to Digg Submit "An Introduction To JUnit" to del.icio.us Submit "An Introduction To JUnit" to StumbleUpon Submit "An Introduction To JUnit" to Google

Tags: junit Add / Edit Tags
Categories
Java SE

Comments