Sunday, 14 September 2014

Writing Parameterized Test Cases in Junit

Many times we want to execute the same test case with different input and expectations. Instead of writing each test separately, it is much better to abstract the actual test into a class and inject input values and expected results into the test class. Junit4 provides Parametrized test, which is a standard solution to achieve this.

Let’s write a simple square() method to return square of a number. We’ll consider this square() method for writing our Parametrized test case:
package blog.techypages.junit.test;

 * Utility class to support various mathematical functions.
 * @author abhishek
public class MathUtils {
     * Returns square of a number
     * @param number
     * @return
    public static int square(int number){
        return number*number;


To write Parametrized test cases a test class should satisfy following conditions:
       1. Test class should be annotated with @RunWith(Parameterized.class) annotation.
       2. Test class should have a static public method annotated with @Parameters annotation and returning                   a collection of test data elements (which in turn are stored in an array).
       3. Test class should have a single constructor which accepts test data elements from the previously                           mentioned array and inject into object appropriate states.

When running a parametrized test class, a new test class is created for the cross-product of the test methods and the test data elements. It means for a test class if there is 1 test case and 5 input data then there will be total 5(1*5) instances of parameterized test class with their own set of input data.

Let’s write Parameterized test to test square() method for inputs [0,5] and their corresponding expectations.
package blog.techypages.junit.test;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

 * Parameterized test case.
 * @author abhishek
public class SquareTest {

    @Parameters(name = "Test#{index}: square[{0}]={1}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] { 
                 {0, 0}, {1, 1}, {2, 4}, {3, 9}, {4, 16}, {5, 25}
    private int input;
    private int expected;
    public SquareTest(int input, int expected) {
        this.input = input;
        this.expected = expected;

    public void testSquare() {
        System.out.println("Test Case Instance: " + this);
        assertEquals(expected, MathUtils.square(input));


Console Prints:
Test Case Instance: blog.techypages.junit.test.SquareTest@2ca6d51e
Test Case Instance: blog.techypages.junit.test.SquareTest@2aca0115
Test Case Instance: blog.techypages.junit.test.SquareTest@340d1fa5
Test Case Instance: blog.techypages.junit.test.SquareTest@4998a455
Test Case Instance: blog.techypages.junit.test.SquareTest@444cee32
Test Case Instance: blog.techypages.junit.test.SquareTest@16aa37a6

It is clearly evident from the console prints that there are total 6(1 test-case*6 input) instances of SqaureTest class.

Identify Individual Test Case
In order to easily identify the individual test cases in a Parameterized test, you may provide a name using the @Parameters annotation. This name is allowed to contain placeholders that are replaced at runtime:

      1. {index}      : the current parameter index
      2. {0}, {1}, … : the first, second, and so on, parameter value

In our example we named the test case as "
Test#{index}: square[{0}]={1}". Actual test names can be easily viewed in the Result snap.

Writing Parameterized test is pretty simple and useful to run the same test for various inputs.

Hope this article helped. Happy learning... :)

Thursday, 14 August 2014

Creating temporary files or folders in Junit

Numerous times we write Junit tests where we need to create temporary files and folders for executing the testcase. Usually, we create temporary folder at some physical location and write temporary files in it. Major pain in this approach is that we need to take care of creation and cleanup of all such files during the test lifecycle.

Junit4 comes with special Rule TemporaryFolder which automatically takes care of all such things. It creates the temp folder when a test starts and deletes the temp folder when the test finishes. It does this for every test method in the class. It will always clean up the files, whether the test passes, fails, or throws an exception.

Under the hood, TemporaryFolder uses the File.createTempFile() method to create the folder, so it's storing the folder in operating system's temp folder. It also assigns a unique name to the folder, so if the JVM crashes and TemporaryFolder does not clean up your files, the results of next test run will not be skewed by the files from the previous run.

Let’s see how it works:
package blog.techypages.junit.test;


import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import blog.techypages.rule.RepeatRule;

 * Class to check some of the usage of @see TemporaryFolder
 * @author abhishek
public class TemporaryFolderTest {
    public RepeatRule repeat = new RepeatRule(10);
    public TemporaryFolder tempFolder = new TemporaryFolder();

    public void sampleTest() throws IOException {
        String writeString = "The quick brown fox jumps over the lazy dog.";
        // 1. Create a temp file.
        File tmpFile = tempFolder.newFile();
        System.out.println("Path: " + tmpFile.getAbsolutePath());

        // 2. Write writeString to this temp file.
        FileUtils.writeStringToFile(tmpFile, writeString);

        // 3. Read content of the temp file
        String readString = FileUtils.readFileToString(tmpFile);

        // 4. Verify: readString and writeString should be equal.
        Assert.assertEquals(writeString, readString);


Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit17809417054081844.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit744343614217417992.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit5848675023725375369.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit3428415497682180161.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit7729225341687093633.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit8396781193866390009.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit7982918886982845418.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit986976126465928150.tmp
Path: C:\Users\ABHISH~1\AppData\Local\Temp\junit8242036959618829704\junit7979718795863279044.tmp

Note: It’s clearly evident from the output that on each repetition newFile() creates a new file within the temporary directory with a random file name[If a file name is not passed into the method, then it will generate a random file name]. Here, we used RepeatRule(10) to repeat the same testcase 10 times. For more information on RepeatRule, please read the previous post “Repeating a test case in Junit”.

Now after the test execution, let’s do a quick look up for the temp folder "junit8242036959618829704" in the system’s temp folder to see whether it exists or not:
C:\Users\ABHISH~1\AppData\Local\Temp>ls | grep "junit8242036959618829704"


You can see that the temp folder "junit8242036959618829704" has been cleaned up by TemporaryFolder.

It’s really very useful feature of Junit, which takes out the pain involved with temp files management in unit testing.

Hope this article helped. Happy learning... :)

Monday, 11 August 2014

Repeating a test case in Junit

Many times we need to create Junit tests which needs to be repeated over and over (may be with different data set). Many of us did this by writing custom Runner or sometimes using parameterized test.

Junit4 comes with @Rule, which can be used for repeating a testcase. Actually, rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way. Using @Rule for such a requirement is preferable because it does things in a more clean way. Moreover by using @Rule we still has option to use pretty useful runners like @RunWith(PowerMockRunner.class) etc.

Let’s create a simple Rule to repeat a test case to ‘N’ number of times:
package blog.techypages.rule;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

 * Rule class to be repeat the same test case over and over.
 * @author abhishek
public class RepeatRule implements TestRule {
    private int count;
    public RepeatRule(int count) {
        this.count = count;
    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            public void evaluate() throws Throwable {
                for (int i = 0; i < count; i++) {


Let’s make a quick testcase and see how it works:
package blog.techypages.rule;

import org.junit.Rule;
import org.junit.Test;

 * Class to demonstrate @see RepeatRule usage.
 * @author abhishek
public class RepeatTest {
    public RepeatRule rule = new RepeatRule(10);
    private int counter = 0;

    public void test() {



It’s really easy and useful feature of Junit. Use it next time and you will find it a great help.

Hope this article helped. Happy learning... :)

Sunday, 8 June 2014

Correct way to check empty string in JAVA

In our day-to-day programming activities, we usually come across multiple scenarios where we need to check whether a string is empty or not.

There are multiple ways to do this check in Java:
  1. equals method: str.equals(“”)
  2. length method: str.length() == 0  //recommended
  3. isEmpty method [From Java 1.6 onward]: str.isEmpty()  //recommended
The recommended way for empty string check is length() or isEmpty() method. We should never use equals(“”) for such a simple requirement.

Let’s have a look on the source code of String class to understand why we should use isEmpty/length:

length() method:
public int length() {
   return count;

isEmpty() method:
public boolean isEmpty() {
   return count == 0;

equals() method:
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            return true;
    return false;

If we observe the source code of the above three methods provided by String class, it is very clear that length() is simply a getter method and returns length of the String. It’s obvious that any String having length 0 is always an empty string and so, the following code is able to detect whether the string is empty or not:
str.length() == 0;

The same reason holds behind using isEmpty() method. Moreover this method seems much verbose by its signature itself.

On the other hand, if we take a look on equals method, it seems to be relatively heavyweight. It does a lot of computation and consumes relatively more CPU cycles for the same operation. So, simply for such a basic check, using equals() method will result in lot of waste of CPU cycles.

Do share your thoughts.
Hope this article helped. Happy learning... :)

Wednesday, 7 May 2014

String Constant Pool In Java

String is a special class in Java. It has very high importance in concurrent programming as well because String is immutable. Since, String is immutable, so they should be reused. In order to reuse String objects JVM maintains a special pool called “String literal pool” or “String constant pool” to store references
of String Objects.

There are slight differences in various methods of creating String objects.

1. Creating String Directly [Using String Literals]:    
String str = “hello”;
All the string literals are created and their references are placed in the pool while JVM loads the class. So, the literal(String Object) "hello" will be created in the heap and have a reference in the pool(at the class load time itself) before execution of the following statement
     String str = “hello”;.
Hence, whenever our code tries to create a String literal, JVM checks the String Literal Pool and since the string already exists in the pool, a reference to the pooled instance is returned back to the caller.

So, String literals used in Java code always refers to the pooled object of String pool.
JVM keeps at most one object of any String in the literal pool.

2. Creating String Using Constructor:
String str = new String(“hello”);
In this case since we are creating String object using “new” keyword, String object will be created in heap memory and this is separate from the String Literal Pool. So, it may happen that String Literal Pool might have the equal String object available but using “new” we will always be able to create different String object with same content.

It is String literals that get automatically interned/added to the String pool. String objects created with the “new” operator do not refer to objects in the String Literal Pool but can be made to by using String’s intern() method. The String.intern() returns an interned String, that is, one that has an entry in the global String Literal Pool. Using intern(), if the String is not already in the global String Literal Pool, then it will be added.

You can inspect constant pool of a class by running javap -verbose for that class.

e.g.: Following code prints “Hello!” (String literal) on console[Compiled with Java 1.6].
package blog.techcypher.stringpool;

 * @author abhishek
public class StringLiteral {

     * main method
     * @param args
    public static void main(String[] args) {


By inspecting the byte code you can easily see that String Literal “Hello!” resides in the Constant Pool.

Compiled from ""
public class blog.techcypher.stringpool.StringLiteral extends java.lang.Object
  SourceFile: ""
  minor version: 0
  major version: 50
  Constant pool:
const #1 = class        #2;     //  blog/techcypher/stringpool/StringLiteral
const #2 = Asciz        blog/techcypher/stringpool/StringLiteral;
const #3 = class        #4;     //  java/lang/Object
const #4 = Asciz        java/lang/Object;
const #5 = Asciz        <init>;
const #6 = Asciz        ()V;
const #7 = Asciz        Code;
const #8 = Method       #3.#9;  //  java/lang/Object."<init>":()V
const #9 = NameAndType  #5:#6;//  "<init>":()V
const #10 = Asciz       LineNumberTable;
const #11 = Asciz       LocalVariableTable;
const #12 = Asciz       this;
const #13 = Asciz       Lblog/techcypher/stringpool/StringLiteral;;
const #14 = Asciz       main;
const #15 = Asciz       ([Ljava/lang/String;)V;
const #16 = Field       #17.#19;        //  java/lang/System.out:Ljava/io/PrintStream;
const #17 = class       #18;    //  java/lang/System
const #18 = Asciz       java/lang/System;
const #19 = NameAndType #20:#21;//  out:Ljava/io/PrintStream;
const #20 = Asciz       out;
const #21 = Asciz       Ljava/io/PrintStream;;
const #22 = String      #23;    //  Hello!
const #23 = Asciz       Hello!;
const #24 = Method      #25.#27;        //  java/io/PrintStream.println:(Ljava/lang/String;)V
const #25 = class       #26;    //  java/io/PrintStream
const #26 = Asciz       java/io/PrintStream;
const #27 = NameAndType #28:#29;//  println:(Ljava/lang/String;)V
const #28 = Asciz       println;
const #29 = Asciz       (Ljava/lang/String;)V;
const #30 = Asciz       args;
const #31 = Asciz       [Ljava/lang/String;;
const #32 = Asciz       SourceFile;
const #33 = Asciz;

public blog.techcypher.stringpool.StringLiteral();
   Stack=1, Locals=1, Args_size=1
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return
   line 8: 0

   Start  Length  Slot  Name   Signature
   0      5      0    this       Lblog/techcypher/stringpool/StringLiteral;

public static void main(java.lang.String[]);
   Stack=2, Locals=1, Args_size=1
   0:   getstatic       #16; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   ldc     #22; //String Hello!
   5:   invokevirtual   #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8:   return
   line 16: 0
   line 17: 8

   Start  Length  Slot  Name   Signature
   0      9      0    args       [Ljava/lang/String;


Some Key Points about String Literal Pool:

  1. An object is eligible for garbage collection if it has no live references from active parts of the JVM/application. In the case of String literals, they always have a reference to them from the String Literal Pool and therefore, they are not eligible for garbage collection until the class and its class-loader is unloaded.
  2. All the string literals are created and their references are placed in the pool while JVM loads the class.
Hope this article helped. Happy learning... :)

Monday, 28 April 2014

Recursion and StackOverflowError in Java

Recursion simply means calling the same function inside its own body repeatedly to complete some task. This is one of the standard approaches to achieve some task. While programming using recursion, there is one basic thing one must fix is the base condition to stop the recursion, otherwise we’ll run into an infinite recursion.

Let’s have a look on a very simple recursive function “sum” which can be used to compute the sum of n numbers.

package blog.techcypher.recursion;

 * Returns the sum of 'n' natural numbers.
 * @author abhishek
public class Sum {
     * @param n
     * @return
    public static int sum(int n) {
        int sum = 0;
        if (n==1) {
            sum = 1;
        } else {
            sum = n + sum(n-1);
        return sum;

     * main method to invoke recursion
     * @param args
    public static void main(String[] args) {
        int n = 1000;
        System.out.print("Sum of [" + n + "] naural numbers: ");


Sum of [1000] naural numbers: 500500

In this example, the base condition is n == 1 i.e. call to sum will be stop when n=1. So, we start summing up numbers starting from n till 1 using recursion.
It works perfectlyJ

But, what will be the depth of recursion for various values of n in the above “sum” function.
Obviously, it will depend on the input. For large values of n like 10000 or more, the program will throw StackOverflowError and JVM may crash.

For n = 10000,
Sum of [10000] naural numbers: Exception in thread "main" java.lang.StackOverflowError
    at blog.techcypher.recursion.Sum.sum(

An obvious question comes into mind is - “Why we are getting StackOverflowError for deep recursion…?”

The reason is “The recursive function may run out of the default thread stack size, and such scenario it throws an Error which is StackOverflowError ”.

In Java, the default thread stack size is 512k in the 32-bit VM, and 1024k in the 64-bit VM on Windows. You may refer link to check the default thread stack size for other OS.

So, what should I do, if I am getting StackOverflowError…?

1. Increase the default thread stack size:
    Java provides run-time argument to tune the default thread stack size using –Xss option.
                java –Xss2048k
     This statement means that the stack size will be 2048KB.
     But notice that it may be curable, but a better solution would be to work out how to avoid
     recursing so much.

 2. Change the implementation to an iterative solution:
    Most of the recursive solutions can easily be converted to iterative solutions, which will
     make the code scale to larger inputs much more cleanly. Otherwise we'll really be guessing
     at how much stack to provide, which may not even be obvious from the input.
     This should the most preferred solution.

3. Using Tail Recursion:
    Using tail-call optimization we are able to avoid allocating a new stack frame for a
     function because the calling function will simply return the value that it gets from
     the called function. The most common use is tail-recursion, where a recursive function
     written to take advantage of tail-call optimization can use constant stack space.
     It is supported by many functional languages but it is not supported by Java.  

Coming to the best practices, we should prefer iterative solution over recursion wherever
possible. This will be relatively faster and scalable.

Hope this article helped. Happy learning… J

Friday, 11 April 2014

Using Unix Commands On Windows

In our day to day life, we need to debug various issues with the help of several log files e.g. application logs, server access logs, error logs etc. and during this process we try to fetch relevant information from the log file(s).

While working on windows with such files, we use various editors like Notepad++, JujuEdit etc. But, what if the log files are really big, somewhere in GB’s…? Most of these editors get hanged while opening or they simply refuse to open such big files because these editors support files up to 2 GB.

For such requirements there are few editors like EmEditor, Glogg etc. which can open big files easily. These editors are really good and very fast for big files.

But here clicks a good question - Can we execute 'grep' like Unix command(s) on such big files in our Windows command prompt...? It would be great if we can get such luxury on windows as well.

Fortunately it’s a “Big YES”. There are several open source software’s which can be used to get most of the Unix Commands running on Windows machine in our familiar Windows command prompt. Few such software's are- UnxUtils, Cygwin etc.

I have been using UnxUtils for a long time now on my Windows machine. It’s a lightweight alternative among similar software’s. Getting started with UnxUtils is pretty simple and easy.

Let’s jump directly on the steps to get UnxUtils working on Windows machine:
  1. Download
  2. Extract the downloaded zip at some location on your windows machine. On my machine I kept it at “D:\Softwares\UnxUtils”
  3. In the PATH environment variable set the path of utility till “wbin” directory. On my machine I set the PATH variable as “D:\Softwares\UnxUtils\usr\local\wbin”
  4. Before moving ahead, verify the PATH setting for “wbin” directory.


It's all set… J
Now, we can to use Unix commands in our Windows command prompt. Let’s quickly check the “grep” command help in Windows Command Prompt:

Hope this article helped. Happy learning!