Thursday, June 27, 2013

Simple Example for using JUnit with Eclipse to test Java source code

This is a very basic tutorial on how to begin with JUnit to perform unit testing of the java source code you have written.

Why should we perform unit testing?

No software in the world can be said to be completely bug free. But it is important that you test what ever piece of software you write and make sure of removing almost all possible bugs. For this we can follow two important principles which most of the experienced programmers follow.
  1. Make your functions simple. Follow the unix design principle. Each function should do only one simple task. Do not complicate your function and let it handle all the possible cases. Follow the principles of ADT. It becomes very easy to test your functions if you follow this principle.  
  2. Think of how to test when you write each function. List down the test cases your function should pass and   most importantly include the test cases for which your function should fail. The function should behave as expected in all possible cases.

So what is JUnit?

JUnit is a framework which can be used to perform unit testing of your java code.

How to use JUnit to Unit Test java code?

Let me explain you this with a very small example. We will have class Calculator which can perform all the 4 basic operations like Addition, Subtraction, Multiplication and Division. Now lets learn how to test these operations using JUnit.

package learn.junit.demo;

public class Calculator {
 
 public double add(double a, double b) {
  return a + b;
 }
 
 public double subtract(double a, double b) {
  return a - b;
 }
 
 public double multiply(double a, double b) {
  return a * b;
 }
 
 public double divide(double a, double b) { 
  if(b == 0) {
   throw new ArithmeticException();
  }
  return a / b;
 }
 
}
Follow the step by step instruction to successfully create and execute the test cases.

Step 1: Create a java Project names Calculator and create a class Calculator as shown above. Now right click on the Calculator class in the eclipse project explorer and select JUnit Test case. If you don't this option, then select New --> Other... --> Java --> Junit --> JUnit Test Case.



Step 2: Enter the name of the test case file, package where it has to be create and also select the setUp() and tearDown() methods if required and click on next



Step 3: Select the methods you want to test and click on finish



Step 4: Now you get a list of test cases, one each for the methods you have implemented in the Calculator class. Now you can write your test cases and execute them.


Step 5: Just copy paste the implementation given below

package learn.junit.demo;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class CalculatorTest {

 private Calculator calc;
 
 @Before
 public void setUp() throws Exception {
  calc = new Calculator();
 }

 @After
 public void tearDown() throws Exception {
  calc = null;
 }

 @Test
 public void testAdd() {
  double result = calc.add(10.5, 20.32);
  assertEquals(30.82, result, 0);
 }

 @Test
 public void testSubtract() {
  double result = calc.subtract(100.5, 100);
  assertEquals(0.5, result, 0);
 }

 @Test
 public void testMultiply() {
  double result = calc.multiply(2.5, 100);
  assertEquals(250, result, 0);
 }

 @Test
 public void testDivide() {
  double result = calc.divide(100, 10);
  assertEquals(10, result, 0.001);
  
 }
 
 @Test(expected = ArithmeticException.class)
 public void testDivideByZero() {
  calc.divide(100.5, 0);
 }

}

Step 6: Now execute the test cases as shown below by right clicking on the CalculatorTest.java and selecting Run As --> JUnit Test


For understanding the JUnit APIs you can refer to the API documentation.

The figure below gives a very brief explanation about the APIs used for implementing the test cases.



Next Blog will be on using EasyMock to mock the interfaces during unit testing.

Saturday, February 2, 2013

Divide and conquer Solution for Maximum Sub Array Problem

Here is C++ code for finding Maximum Sub-Array in a given array using Divide and conquer approach. The program follows the logic given in the book "Introduction to Algorithms".

So what is Maximum Sub Array?
Maximum sub-array is the sub array with largest sum.
For example for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous sub-array with the largest sum is 4, −1, 2, 1, with sum 6.

#include<iostream>
#include<vector>
#include<cstdlib>
#define MINUS_INFINITY -99999

using namespace std;

/*array of elements and its size*/
vector<int> a;
int size;

/*
 * function to find the max sub array in the mid
 */
void max_sub_array_in_mid(int l, int h, int *sum, int *low, int *high) {
    
    int current_sum;
    int l_sum = MINUS_INFINITY;
    int r_sum = MINUS_INFINITY;
    int mid = (l+h)/2;

    current_sum = 0;
    for(int i = mid; i >= l; i--) {
        current_sum += a[i];
        if(current_sum > l_sum)
        {
            l_sum = current_sum;
            *low = i;
        }
    }

    current_sum = 0;
    for(int i = mid+1; i <= h; i++) {
        current_sum += a[i];
        if(current_sum > r_sum) {
            r_sum = current_sum;
            *high = i;
        }
    }

    *sum = l_sum + r_sum;
}

/*
 * This function gets called recursively to find the max sub array 
 * which could be on left/right of mid or the one that is in between
 */
void max_sub_array(int l, int h, int *sum, int *l_index, int *r_index) {
    
    if(l==h) {
        *sum = a[l];
        *l_index = l;
        *r_index = l;
    }
    else {
        int mid = (l+h)/2;
        int l_low,l_high,l_sum;
        int r_low,r_high,r_sum;
        int mid_low,mid_high,mid_sum;

        max_sub_array(l, mid, &l_sum, &l_low, &l_high);
        max_sub_array(mid+1, h, &r_sum, &r_low, &r_high);
        max_sub_array_in_mid(l, h, &mid_sum, &mid_low, &mid_high);
        
        if(l_sum > r_sum && l_sum > mid_sum) {
            *sum = l_sum;
            *l_index = l_low;
            *r_index = l_high;
        }
        else if(r_sum > l_sum && r_sum > mid_sum) {
            *sum = r_sum;
            *l_index = r_low;
            *r_index = r_high;
        }
        else if(mid_sum > r_sum && mid_sum > l_sum) {
            *sum = mid_sum;
            *l_index = mid_low;
            *r_index = mid_high;
        }
    }
}

int main() {
    
    int sum = 0;
    int l_index = -1;
    int r_index = -1;

    cout<<"\nEnter array size\n";
    cin>>size;

    for(int i=0;i<size;i++) {
        //more weightage for negative numbers to generate good test cases
        a.push_back(rand()%100 - rand()%150);
    }
    
    cout<<"\n array is \n";
    for(int i=0;i < size;i++) {
        cout<<a[i]<<" ";
    }
    cout<<endl;

    //Algorithm begins here
    max_sub_array(0, size-1, &sum, &l_index, &r_index);

    cout<<"\n max sub array ranges from "<<l_index<<" to "<<r_index<<endl;
    cout<<"array is:\n";
    for(int i=l_index;i<=r_index;i++)
        cout<<a[i]<<" ";
    cout<<endl;

    return 0;
}

Thursday, January 31, 2013

Creating a Shared Library in C using GCC

This post is about how to create a shared library in C using the GCC Compiler.
Often we are only used to writing small C programs which might contain small functions, all of which are in the same file. Hence its very easy and straight forward to compile and get it working.

However this is not the case when our program is spread across over in many files. In which case we will have to compile each of them individually and link them together to form a final executable file. So let me walk you through a small example on how to compile a small "Hello World" program which spans across 3 different files.

Let us have 3 files here.
File 1 ==> A Header file (hello.h) which contains the declaration of hello() function
File 2 ==> A source file (hello.c) which contains the implementation of hello() function
File 3 ==> Another source file (main.c) which uses the function hello()

So out task is now here to create the first two files and create a shared library using them so that we can use the function hello() from the shared library in any program then after.

The two files hello.h and hello.c are as shown below:


/* hello.h */

#include
void hello();


/* hello.c */

#include "hello.h"
void hello() {
    printf("\nHellow World!!\n");
}


Now lets build a shared library after compiling them individually using commands below
gcc -c hello.h
gcc -c hello.c
gcc -Wall -shared -fPIC -o libhello.so example.c

In the above command we are creating a shared library named libhello.so
Remember to prefix your library name with "lib" and have an an extension as .so

Now that our shared library is ready, all we are left out with is to create a main.c file where the function hello() is being used and compile and link that file with our shared library.

Here is out main.c file

/* main .c */

#include"hello.h"
int main() {    
    hello();
    return 0;
}


Compile it as below
gcc -c main.c

Now to link this main.c with shared library we can use -L and -l options as below
gcc main.c -L . -lhello

In above command "dot" specifies the current directory. If our shared library was in some other directory then we can specify the path using -L option as shown below
gcc main.c -L <shared_lib_location>  -lhello

And -lhello tell gcc to look for a library named libhello.so


Now that we have compiled and linked our main.c file; we can execute and see the output as below
./a.out 
Hellow World!!

In my next post I shall discuss about make files!!

Wednesday, January 30, 2013

Installing Network Simulator (NS2) on Ubuntu 10.04

This is my blog after quite a long time on how to install NS on Ubuntu 10.04
This works on Ubuntu 10.04. You can experiment for later versions.


I have provided a script which will help you perform all the steps automatically. Simply download the script from here and execute it with root privilege as below. Execute it at your own risk :P
  • sudo su 
  • chmod +x script.sh
  • . script.sh (find a dot and a space before the file name)

(or) 

Do execute the commands one by one manually to perform the installation.

  1. sudo apt-get update
  2. sudo apt-get build-essential autoconf automake libxmu-dev
  3. Download Net Sim from here
  4. tar -xvf ns-allinone-2.35.tar.gz
  5. for simplicity I am moving the extracted directory to directory named ns2 under home directory
  6. mv ns-allinone-2.35 ~/ns2 
  7. cd ns2/
  8. ./install
  9. Once the installation is done, you will be provided with the following path information
    • LD_LIBRARY_PATH
    • TCL_LIBRARY_PATH
    • PATH
    • TCL_LIBRARY
  10. Copy paste the above path information into your .bashrc (find a preceding dot) file as below
    • export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/xyz/ns2/otcl-1.14
    • export TCL_LIBRARY_PATH=$TCL_LIBRARY_PATH:/home/xyz/ns2/tcl8.5.10/library
    • export PATH=$PATH:/home/xyz/ns2/bin:/home/xyz/ns2/tcl8.5.10/unix:/home/xyz/ns2/tk8.5.10/unix
    • export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/xyz/ns2/otcl-1.14:/home/xyz/ns2/lib
    • export TCL_LIBRARY=$TCL_LIBRARY:/home/xyz/ns2/tcl8.5.10/library
  11. Save the .bashrc file and source the file using command below
    •  . .bashrc   (or)   source .bashrc
  12. All done and now test your installation with command below (This is optional. You can skip this step. This step will take some time and performs various tests on your installation and give you results.)
    • /ns2/ns-2.35/validate 
  13. now type ns or nam to start your Net Sim...