JUnit Tutorial
Here is really brief JUnit Tutorial. Without a wait, lets start.
What you need ?
- JDK
- Ant (http://ant.apache.org)
- JUnit (http://www.junit.org)
Make sure that you have all of the jars in right place.
Let’s Start !
You need a piece of code that you want to test with JUnit, we will start with this simple example :
public class Math {
       static public int addMee(int int1, int int2) { Â
               return int1 + int2;
       }
}
What it will do ?, just add two numbers. Now you need to write a piece of code that you will be writing to test. For this, you need :
- import junit.framework.*
- extend TestCase.
Here’s an example JUnit piece of Code.
import junit.framework.*;
public class TestMath extends TestCase {
 public void testAdd() {
       int num1 = 3;
       int num2 = 2;
       int total = 5;
       int sum = 0;
       sum = Math.addMe(num1, num2);
       assertEquals(sum, total);
 }
}
There are couple of things that you need to look for :
- The method is named testAddNumbers. This convention tells you that the routine is supposed to be a test and that it’s targetting the “addNum” functionality.
- Now how to you run yout test code ?, here we use Ant to do the task for us (you can also use command line, Eclipse or the JUnit Test Runner). To run a Junit test with an Ant script, add this to your Ant script:
<junit printsummary=”yes” haltonfailure=”yes” showoutput=”yes” >
       <classpath>
               <pathelement path=”${build}”/>
       </classpath>                  Â
       <batchtest fork=”yes” todir=”${reports}/raw/”>
               <formatter type=”xml”/>
               <fileset dir=”${src}”>
                       <include name=”**/*Test*.java”/>
               </fileset>
       </batchtest>
</junit>
    Â
Ant will also do nice things like create nice HTML reports for you!, and this is all and should be enough for you to understand the basics of Junit.







