Saturday, December 31, 2011

Creating a Junit Test Class

The Procedure to create a JUnit Test Class is as follows:
1. There are many ways to create a JUnit Test Case Class.
  1. Select File > New > JUnit Test Case
  2. Select the arrow of the  New icon (shown at the end of the post)  in the upper left of the toolbar. Select JUnit Test Case,
  3. Right click on a package in the Package Explorer view in the Java Perspective, and select JUnit Test Case, or
  4. Click on the arrow of the  New Java Class icon (shown at the end of the post)  in the toolbar. Select JUnit Test Case.
  5. You can create a normal Java class as shown in the Eclipse tutorial, but include junit.framework.TestCase as the super class of the test class you are creating.
  6. Right click on an application class that you want to create a test class for, and select New > JUnit Test Case.
    2. In the wizard for creating a new JUnit test case classes
    • The source folder specifies where you want to create the test case. Based on the project hierarchy presented in previous post, we want to create the new test case in the tests/ source folder.(in our case 'ExampleJunit/tests' )
    • Next, specify the package you want your test case to belong to. If you are associating your test case with an application class, then you will want both of these classes to share the same package so you can take advantage of package level visibility when testing your application class.(in our case 'test' )
    • Specify the test case name. If you are associating your test case with an application class the convention is that the test case name is the application class name followed by Test.(in our case 'SampleTest')
    • JUnit has several standard methods that are useful for testing. setUp() and tearDown() methods are run before and after each test method.
    • If you are associating your test case with an application class, then Browse for the application class in the Class under test field.
    3. If you selected a Class under test you can click the Next button to select which methods you want to write test cases for. The method signatures will be created for you. Click Finish and the new test case class will open in the editor.

      4. Below is a test case template from the JUnit 3 .This test class demonstrates the basic functionality of the setUp() andtearDown() methods, and gives example test cases. The testForException() method demonstrates how to test that an exception is properly thrown.  

      Note:All source methods in the class under test must be public or protected, not private, in order to be tested by JUnit. If the method in the class under test is protected, the test class must be in the same package. 
      1. import junit.framework.TestCase;
      2. public class SampleTest extends TestCase {
      3.     private java.util.List emptyList;
      4.     /**
      5.     * Sets up the test fixture.
      6.     * (Called before every test case method.)
      7.     */
      8.     protected void setUp() {
      9.       emptyList = new java.util.ArrayList();
      10.     }
      11.     /**
      12.     * Tears down the test fixture.
      13.     * (Called after every test case method.)
      14.     */
      15.     protected void tearDown() {
      16.       emptyList = null;
      17.     }
      18.     public void testSomeBehavior() {
      19.       assertEquals("Empty list should have 0 elements", 0, emptyList.size());
      20.     }
      21.     public void testForException() {
      22.       try {
      23.            Object o = emptyList.get(0);
      24.            fail("Should raise an IndexOutOfBoundsException");
      25.       }
      26.       catch (IndexOutOfBoundsException success) {
      27.       }
      28.     }
      29. }
      5. Below is a test case template based on the examples presented in the Junit 4.This test class demonstrates the basic functionality of the setUp() and tearDown() methods, and gives example test cases.The testForException() method demonstrates how to test that an exception is properly thrown.

      Note: All source methods in the class under test must be public or protected, not private, in order to be tested by JUnit. If the method in the class under test is protected, the test class must be in the same package. 
      1. import org.junit.*;
      2. import static org.junit.Assert.*;
      3. public class SampleTest {
      4. private java.util.List emptyList;
      5.     /**
      6.      * Sets up the test fixture.
      7.      * (Called before every test case method.)
      8.      */
      9.     @Before
      10.     public void setUp() {
      11.         emptyList = new java.util.ArrayList();
      12.     }
      13.     /**
      14.      * Tears down the test fixture.
      15.      * (Called after every test case method.)
      16.      */
      17.     @After
      18.     public void tearDown() {
      19.         emptyList = null;
      20.     }
      21.     @Test
      22.     public void testSomeBehavior() {
      23.         assertEquals("Empty list should have 0 elements", 0, emptyList.size());
      24.     }
      25.     @Test(expected=IndexOutOfBoundsException.class)
      26.     public void testForException() {
      27.         Object o = emptyList.get(0);
      28.     }
      29. }
      Icons Used:
          
       
         New

      New Java Class

      Start With JUnit

      Important Points :
      • It is considered a best practice in testing, to separate the test case code from the application code. Typically the application code is in a source folder called src/ while the test code is in a source folder called tests/.
      • Below is the file structure for a JUnit Project ,example
      Project Hierarchy
      • To run JUnit test cases the JUnit libraries must be on the classpath
      • The JUnit library is required to be on the project classpath to compile and run the JUnit test cases. If your JUnit library isn't set up correctly, there will be an warning message at the top of the Java Build Path window.
      Steps for adding junit jar on the Build Path :
      1. Right click on the project and select Properties. In the left column select Java Build Path and select the Libraries tab.
      2. Select the Add Library... button to the right of the window. Select JUnit from the library list, and press the Next > button
      3. Use the drop down box to select the version of JUnit that you want to use for your project. 
      OR
      1. Right click on the project and select Properties. In the left column select Java Build Path. To the right select the Libraries tab. Click the Add External JARs... button. You should start off in the Eclipse install directory, otherwise search through the file system until you find the Eclipse install directory.
      2. Under the Eclipse install directory select plugins/org.junit_XXX/junit.jar. Click OK.
      OR
      1. Download junit.jar from www.junit.org. Add junit.jar to your lib/ directory in your project.
      2. Right click on the project and select Properties. In the left column select Java Build Path. To the right select the Libraries tab. Click the Add JARs... button. Select your project, and go down through the tree until you find junit.jar under the lib folder. Select junit.jar and Click OK.


      About JUnit


      JUnit is an open source unit testing framework for automatically unit testing Java programs.  
      JUnit provides functionality for writing and running unit test cases for a project under development.

      Mainly there are two versions of JUnit
      I.JUnit3
      II.JUnit4

      I.JUnit 3 uses specific naming conventions for identifying test classes, methods, and suites.
      These naming conventions are described below:
      1. Test Case Class: Named [classname]Test.java, where classname is the name of the class that is being tested.
      2. Test Case Method: Named test[methodname], where methodname is the name of the method that is tested.
      3. Test Suite: Default name for Eclipse is AllTests.java.
      4. Test Set Up: setUp(),Called before every test case method.
      5. Test Tear Down: tearDown(),Called after every test case method.

      II.JUnit 4 uses annotations (which are keywords that start with @) to identify test classes, methods, and suites.The key annotations are described below:
      1. Test Case Class: Named [classname]Test.java, where classname is the name of the class that is being tested.
      2. Test Case Method: Annotate the method with @Test. The method name does not have to start with test.
      3. Test Suite: Only write a suite() method if you want to run your JUnit 4 tests with the JUnit 3.8 test runner.
      4. Test Set Up: Annotate the method with @Before .
      5. Test Tear Down: Annotate the method with @After .


      Tuesday, December 06, 2011

      Logging using java.util.logging.Logger (Custom logging)

      Sometimes in our application we need to log different messages like info,warning,error etc.Here i have given a way how we can use it in our application.
      Following 'Log' class creates different log files taking different logger value by input and it also maintains the directory structure of log files according to the value of 'path'  passed to the constructor of 'Log' class.For example, if we 'll pass a parameter 'utils.Example',it will create a file 'logs/utils/Example.log' in the current directory.
      Note:First it checks for the directory 'logs/utils' is present or not if it is not present it creates the directory.

      //Log.java
      1. package utils;
      2. import java.io.File;
      3. import java.io.IOException;
      4. import java.util.logging.FileHandler;
      5. import java.util.logging.Logger;
      6. import java.util.logging.SimpleFormatter;
      7.  
      8. public class Log {
      9.  
      10.   static FileHandler handler;
      11.   static Logger logger;
      12.  
      13.   public static void createLog(String path){
      14.     try {
      15.       String [] s = path.split("\\.");
      16.       File f = new File("./"+"logs/"+s[s.length-2]);
      17.       if(f.exists()==false){
      18.         f.mkdirs();
      19.       }
      20.       handler = new FileHandler("logs/"+s[s.length-2]+"/"+s[s.length-1]+".log");
      21.       handler.setFormatter(new SimpleFormatter());
      22.       logger = Logger.getLogger(path);
      23.       logger.addHandler(handler);
      24.      } catch (IOException e) {
      25.         e.printStackTrace();
      26.      }
      27.   }
      28.  
      29.   public static void loggerINFO(String msg){
      30.      logger.info(msg);
      31.   }
      32.  
      33.   public static void loggerWARN(String msg){
      34.      logger.warning(msg);
      35.   }
      36.  
      37.   public static void loggerERROR(String msg){
      38.      logger.severe(msg);
      39.   }
      40. }
      //Example.java
      1. package utils;
      2. import static utils.Log.loggerINFO;
      3. import static utils.Log.loggerWARN;
      4. import static utils.Log.loggerERROR;
      5.  
      6. public class Example {
      7.  
      8.    public Example() {
      9.      Log.createLog(this.getClass().getName());
      10.    }
      11.  
      12.    public void method1(){
      13.      loggerINFO("Doing division by zero");//Log an INFO message
      14.      loggerWARN("May get ArithmeticException");//Log a WARNING message
      15.      try {
      16.        int i = 20/0;
      17.      } catch (Exception e) {
      18.        loggerERROR(e.getMessage());//Log a SEVERE message
      19.      }
      20.    }
      21.  
      22.    public static void main(String[] args) {
      23.      new Example().method1();
      24.    }
      25. }
      After running this we 'll get a log file 'logs/utils/Example.log' (In eclipse,if 'Example.java' is in 'utils' package ,you 'll find a log file 'Example.log' in the 'logs' folder which is generated parallel to 'src' folder of the current project)
      Note: Everytime you run the 'utils/Example.java' you 'll get a fresh file with new content.

      //Content of 'logs/utils/Example.log' after running 'utils/Example.java'

      Dec 6, 2011 6:37:33 PM utils.Log loggerINFO
      INFO: Doing division by zero
      Dec 6, 2011 6:37:33 PM utils.Log loggerWARN
      WARNING: May get ArithmeticException
      Dec 6, 2011 6:37:33 PM utils.Log loggerERROR
      SEVERE: / by zero