In computer programming, a unit test is a method of testing the correctness of a particular module of source code. The idea is to write test cases for every non-trivial function or method in the module so that each test case is separate from the others if possible.

JUNIT: A testcase framework for Java

 

In computer programming, a unit test is a method of testing the correctness of a particular module of source code. The idea is to write test cases for every non-trivial function or method in the module so that each test case is separate from the others if possible.

Advantages
The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. It provides a written contract that the piece must satisfy. This isolated testing provides two main benefits:

  • Encourages change
    Unit testing allows the programmer to refactor code at a later date, and make sure the module still works correctly (regression testing). This provides the benefit of encouraging programmers to make changes to the code since it is easy for the programmer to check if the piece is still working properly.
  • Simplifies Integration
    Unit testing helps eliminate uncertainty in the pieces themselves and can be used in a bottom-up testing style approach. By testing the parts of a program first and then testing the sum of its parts will make integration testing easier.
  • Documentation
    As an added value, all your Testcases can act as a documentation for your set of classes

Kent Beck, (CSLife) and Erich Gamma, (OTI Zürich) have made a very good article:
"Testing is not closely integrated with development. This prevents you from measuring the progress of development- you can't tell when something starts working or when something stops working. Using JUnit you can cheaply and incrementally build a test suite that will help you measure your progress, spot unintended side effects, and focus your development efforts." more here

Limitations
It is important to realize that unit-testing will not catch every error in the program. By definition, it only tests the functionality of the units themselves. Therefore, it will not catch integration errors, performance problems and any other system-wide issues. Unit testing is only effective if it is used in conjunction with other software testing activities.

Usage
There is a lot of ways to use JUNIT:

  • Write your set of classes, then some Testcase that should run and validate the work done,
  • Write Testcases first that won't run because no classes are existing yet, then write the code that will make it run!
  • Correct a bug in a piece of code, and write a Testcase for being sure that it won't reappear one day.

Junit is based on fact that you want to test a code. Normally you know the result expected, all you have to do is to ask your code (class, method, set of cooperating class) and to test if the response is correct.
Let's take an example.... I have a Class that can replace patterns in a string (like in JDK 1.4.2: "aText".replace("seachPattern","withThisPattern"))). Since I wrote the class, and know the purpose of it, I can write some pertinent testcases. I want to protect this Object and all other Object that may use it from loss of functionnality, bugs which may lead to malfunction in a complex system.

Writing good Testcases

There is no rule how to write a test, but remember

  • That a testcase should be pertinent, otherwise it will have no quality impact and will lead to a loss of developer time.
  • Be honest: push your Objects to the limit of their usage! try to describe and test all functionnality of your set of objects.
  • You need to do some dummy/obvious assertions (but sometimes these dummy tests are not obvious with complex object and or runtime environment).
    Constructor should not give back the same instance
    (Except if you are using a singleton pattern)
    ClassA classA = new ClassA();
    ClassA classA1 = new ClassA();
    assertNotEquals(classA, classA1);
    

The JUNIT language

JUnit use some primitives methods to achieve regression testing. As today in JUNIT 1.3.8, The assertion methods are all located in junit.framework.Assert A lot of third party tools has been developed to extends possibilities of tests with database, EJB, JSP for example.

  • Assert methods are testing equality of nearly all Java standard type
  • If these methods are not enough, you can always decide to validate your objects by Your own and call fail() if you decide that conditions are not met.

Write your first Testcase

A Junit test is a classe which extends junit.framework.Tescase and has some methods beginning with the word "test"

A trivial example:

Your first JUNIT testcase classe
public class SquareTest extends junit.framework.TestCase {
        public void testClassA {
        
         Square squareA = new Square();
         Square squareB = new Square();
        
         assertNotEquals(squareB,squareA);
         assertEquals(squareA.getName(),"ClassA a dummy example");
        
         //verify setter, getter
         squareA.setX(2);assertEquals(2,squareA.getX());
         squareA.setY(4);assertEquals(4,squareA.getY());
        
         //perimeter of a square is 2X+2y
         assertEquals(12,squareA.getPerimeter());
         //surface
         assertEquals(8,squareA.getSurface());
        }

        public void testCloneability() {
        
         Square squareA = new Square();
         squareA.setX(10);
         
         Square squareB = (Square) squareA.clone();
        
         //if Square do not implemeent Comparable, the following is true
         assertNotEquals(squareA,squareB);
         
         //test deep Clone
         assertEquals(10,squareB.getX());
        }
}

Writing a Testcase is always more or less the same:

  1. Create one or more classes extending junit.framework.Tescase and implement some test methods
  2. Create in these methods instances of the object you want to test or validate.
  3. Use your object, use setter and getter, constructor to change their internal state (here is the concept of pushing your object to the limits: use the full range of input data accepted by your objects)
  4. Test values returned by methods, assuming that you know what would be the correct result,
  5. Write a lot of them to test the maximum of functionnalities provided by your objects.

Run your testcases
Different TestRunner or how to run your suite of testcases

A TestRunner is able to run JUNIT testcases, there is more or less 2 categories:

  • Textual TestRunner (console output)
    • The fastest to launch and can be used when you don't need a red green success indication. This is recommended with ANT.
  • Graphical TestRunners (client server web GUI, swing, AWT in eclipse ....)
    • They show a simple graphical dialog to start/stop and display results of tests and provide some graphical progress indication.

A TestRunner can be configured to be either loading or non-loading. In the loading configuration the TestRunner reloads your class from the class path for each run. As a consequence you don't have to restart the TestRunner after you have changed your code. In the non-loading configuration you have to restart the TestRunner after each run. The TestRunner configuration can be either set on the command line with the -noloading switch or in the junit.properties file located in the "user.home" by adding an entry loading=false.

JUNIT find all testcase using java.lang.reflexion package, in fact it will call all methods starting with the word test will be found.

In a JAVA main class:
String[] listUnitTest = {ClassA.class.getName(), ClassB.class.getName()}; //list of classname containing your units tests
junit.textui.TestRunner.main(listUnitTest); //Text based
junit.awtui.TestRunner.main(listUnitTest); //green mean all test successful red is bad in case of error, you see the stack and which test failed.
junit.swingui.TestRunner.main(listUnitTest); //green mean all testcases successful red is badin case of error, you see the stack and which test failed.
JUnit Testrunner in Eclipse is a standar View

Testsuite
Testsuite is a suite of testcase or method, you can give this testsuite to a testrunner.

Some particular TestSuite

Multi threading test
If you need to have multiple threads hitting your class. ActiveTestSuite starts each test in its own thread However, ActiveTestSuite does not have a constructor which automatically adds all testXXX methods in a class to the test suite. I tried addTestSuite method with class name as the argument, but it added all tests in the class to run sequentially in the same thread. So, I had to manually add each test name to the ActiveTestSuite.
public static Test suite() {
TestSuite suite = new ActiveTestSuite();
suite.addTest(new com.waltercedric.junit.ClassA ("testClonability"));
suite.addTest(new com.waltercedric.junit.ClassA ("testSerialization"));
suite.addTest(new com.waltercedric.junit.ClassA ("testRandom"));
return suite;
}

public static void runTest (String[] args) {
junit.textui.TestRunner.run( suite() );
}

Extensions
JUNIT can be extended with 3rd party extensions, if you need some specials capabilities, refer to this page: JUNIT extensions

 

You might like also

Apache POI list of Excel supported functions
The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and …
2379 Days ago
Apache POI Speed Optimizations
The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and …
2547 Days ago
No Thumbnail was found
The AIAA (American Institute of Aeronautics and Astronautics) paper [.pdf] plan to use java (For cost reasons) for safety-critical missions. The first fully time-deterministic and open-source library for Java: Javolution is ready to fight! Javolution real-time goals are simple: To make your application faster and more time predictable! That being accomplished through: High performance and time-deterministic (real-time) util / lang / text / io / xml base classes. Context programming in order to achieve true separation of concerns …
4400 Days ago
Playing with Axis C++ and Apache 1.3.1
Here is a How to since it take me a very long time to install something which should have been trivial....For the benefit of the community, I am publishing it here on my free time :-) ... Enjoy...Apache Axis and Apache Axis C++ are implementation of the SOAP ("Simple Object Access Protocol") submission to W3C. From the W3C draft specification: SOAP is a lightweight protocol for exchanging structured information in a decentralized, distributed environment. It is an XML based protocol …
4946 Days ago
No Thumbnail was found
5241 Days ago
iText a free Java library
iText is a library that allows you to generate PDF files on the fly. The iText classes are very useful for people who need to generate read-only, platform independent documents containing text, lists, tables and images. The library is especially useful in combination with Java(TM) technology-based Servlets: The look and feel of HTML is browser dependent; with iText and PDF you can control exactly how your servlet's output will look.iText requires JDK 1.2. It's available for free under a multiple …
5251 Days ago
No Thumbnail was found
Log4J: A logging framework for J2EE Log4j homepage: http://jakarta.apache.org/log4j/ Reference book on log4j: The Complete Log4j Manualby Ceki GulcuEdition: Paperback IntroductionLog4j is an open source tool (OSS) developed for inserting logs statements into your application and was developed by people at Apache fundation. It's speed and flexibility allows log statements to remain in shipped code while giving the user the ability to enable logging at runtime without modifying any of the application binary. All of this while not incurring a …
5525 Days ago
Apache Jmeter
 Work in progress …
5528 Days ago