Skip to main content

JUnit Getting Started

Main object:   Write a test case using JUnit as simple as possible.
Approach:   First write a class, then write the TestCase and the TestSuite.
Readers:   Should have some experience or knowledge in Java

by Kamal Mettananda

JUnit is a regression testing framework written by Erich Gamma and Kent Beck. This is used by developers to implement unit tests in Java.

Why unit testing is needed?
With unit testing the end product is completely checked for the correcteness of the code. With the time, the set of tests grow and the ease of testing improves. One of the most important things is that developers can be confident on the code and less time needed for debugging.

What is JUnit?
JUnit is a Test framework. The features available are;
  • Assertion methods (test methods)
  • Running tests (TestRunner)
  • Aggregating tests (test suites)
  • Reporting results (text based and GUI based)
One factor that developers may worry is : the developers has to write tests.

Writing a JUnit Test in 5 minutes
First add the junit.jar file to the project (All the following classes are tested using junit-3.8.1.jar). Then write the follwing classes.

Writing JUnit class
  1. Define a subclass of TestCase.
  2. Override the setUp() & tearDown()methods.
  3. Define one or more public testXXX()methods
    all the methods starting with test will be run by the TestRunner
    • call the methods of tested object
    • check the expected results with assertXXX() methods
  4. Define a static suite() factory method
  5. Create a TestSuite class containing all the tests.
  6. Optionally define main() to run the TestCase in batch mode.

1. Write a class - Calc.java


package com.parcelhouse.myproj;

public class Calc {

     public Calc() {
          super();
     }
     public int add(int a, int b){
          // errorneous method
          return a+b+1;
     }
     public int multiply(int a, int b){
          return a*b;
     }
}


2. Write the test case - TestCalc.java (anyname can be used)


package test.com.parcelhouse.myproj;

import junit.framework.TestCase;
import com.parcelhouse.myproj.Calc;//testing class

public class CalcTest extends TestCase {

     Calc c = null;

     public CalcTest(String name) {
          super(name);
     }

     protected void setUp() throws Exception {
          super.setUp();
          c = new Calc();
     }

     /*
      * Test method for 'com.parcelhouse.myproj.Calc.add(int, int)'
      */
     public void testAdd() {
          int x = c.add(5,6);
          assertEquals(11, x);
     }

     /*
      * Test method for 'com.parcelhouse.myproj.Calc.multiply(int, int)'
      */
     public void testMultiply() {
          int x = c.multiply(5,6);
          assertEquals(30, x);
          }

     public static void main(String[] args) {
          junit.textui.TestRunner.run(CalcTest.class);
     }
}

  • Run test case using;
    >java CalcTest

  • The line junit.textui.TestRunner.run(CalcTest.class) is where the trick occurs. The TestRunner runs all the methods in the CalcTest class which has testXXX() signature using reflection.

  • c.add(5,6) line should return 11 if the method works fine. The return value is checked against the expected value in the assertXXX() method.
    As the method is errorneous, this throws junit.framework.AssertionFailedError.
    But the multiply() method works fine and causes no errors.

3. Write the Test Suite - TestSuite.java (anyname can be used)


package test.com.parcelhouse.myproj;

import junit.framework.Test;
import junit.framework.TestSuite;

public class Tests {
     public static void main(String[] args) {
          junit.textui.TestRunner.run(Tests.class);
          //junit.swingui.TestRunner.run(Tests.class);
          //junit.awtui.TestRunner.run(Tests.class);
     }
     public static Test suite() {
          TestSuite suite = new TestSuite("Test for test.com.parcelhouse.myproj");
          //$JUnit-BEGIN$
          suite.addTestSuite(CalcTest.class);
          suite.addTestSuite(ComputerTest.class);//another test case
          //$JUnit-END$
          return suite;
     }
}

  • Run Tests class with >java Tests
    all the testXXX() methods in all the testCases which are added to TestSuite inside suite() method are called.
  • junit.textui.TestRunner.run() gives results in text mode.
    But if junit.swingui.TestRunner.run() or junit.awtui.TestRunner.run() used, results come in UI mode.
  • Add the TestCase to the TestSuite inside suite() method, when ever a new TestCase is needed.

Oh! you are done. The complete TestSuite is completed.
One important thing to keep in mind, write code to do small operations as much as possible.

If you have any question or comment, just add as a comment and will be here to help you guys.

References:
www.junit.org
www.javaworld.com/javaworld/jw-12-2000/jw-1221-junit.html
www.admc.com/blaine/howtos/junit/junit.html

Comments

  1. Nice and easy tutorial. Good work.

    ReplyDelete
  2. Hi Kamal,

    This is Ranganath(java developer),Im really Appreciates u and happy with your post(JUnit Getting Started).This is very usefull for who dont know the junit basics.

    regards,
    Ranganath Parvataneni

    ReplyDelete
  3. Thanks Ranganath.
    Wait for the upcoming Cactus tutorial.

    ReplyDelete
  4. Dude...it was cool compact tut man...I have used junit b4 but this one is kinda recap of everything i know about junit...kudos...
    B4 cactus tutorial...just give the where we use it and under what circumstances we use that...and how to project that skill resume's would defnetly fetch sth for us....

    So loooking forward for your cactus ...cya...A Developerr

    ReplyDelete
  5. Yes sure, I'll try to publish the cactus tutorial soon.

    ReplyDelete
  6. Kamal,

    Thanks a lot....A good tutorial to begin with Junit... I just executed...Hope to see Many from you.....

    Karthik,
    java Developer

    ReplyDelete
  7. Thanks for the appreciation Karthik.

    I'm planning for publishing another tutorial when ever I get sometime.

    Is there any specific subjects that you prefer for a tutorial?

    ReplyDelete
  8. very good tutorial to start with. Many thanks......

    ReplyDelete

Post a Comment

We appreciate your opinions, suggestions and criticism.

Popular posts from this blog

Web Services with Apache Axis 1.4 Tutorial: server and client sides

Java Sorting: Comparator vs Comparable Tutorial

Creative Commons License Digizol by Kamal Mettananda is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License .
URL of this page must be supplied in attribution
© 2004-2017