Monday, 2 July 2018

Junit: ExpectedException rule: check the method is throwing specific exception

By using @ExpectedException rule, you can verify that your code throws a specific exception with given message.

Find the below working example.

Arithmetic.java
package com.sample.arithmetic;

public class Arithmetic {

 public int divide(int a, int b) {
  if (b == 0) {
   throw new IllegalArgumentException("Division by zero is not supported");
  }

  return a / b;
 }
}

ArithmeticTest.java
package com.sample.arithmetic;


import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {
 @Rule
 public ExpectedException expectedException = ExpectedException.none();

 @Test
 public void divide_10By0_IllegalArgumentException() {

  Arithmetic obj1 = new Arithmetic();

  expectedException.expect(IllegalArgumentException.class);
  expectedException.expectMessage("Division by zero is not supported");

  obj1.divide(10, 0);

 }
}


Run the application, you can see below kind of report.


expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Division by zero is not supported");
Above statements check that the code is throwing ‘IllegalArgumentException’ with the message "Division by zero is not supported".

Assumptions and ExpectedException rule
You should call assumption methods before setting the expectations of ExpectedException rule. By setting the assumption before ExpectedException rules, test will not execute if the assumptions are not met.

ArithmeticTest.java
package com.sample.arithmetic;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assume.assumeTrue;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {
 @Rule
 public ExpectedException expectedException = ExpectedException.none();

 @Test
 public void divide_10By0_IllegalArgumentException() {

  Arithmetic obj1 = new Arithmetic();

  assumeTrue(false);

  expectedException.expect(IllegalArgumentException.class);
  expectedException.expectMessage("Division by zero is not supported");

  obj1.divide(10, 0);

 }
}


When I ran ArithmeticTest.java, I observed that the test divide_10By_0_IllegalArgumentException() is skipped  from execution.

If you put assumptions after the ExpectedException rule, the test case is failed.

ArithmeticTest.java

package com.sample.arithmetic;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assume.assumeTrue;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {
 @Rule
 public ExpectedException expectedException = ExpectedException.none();

 @Test
 public void divide_10By0_IllegalArgumentException() {

  Arithmetic obj1 = new Arithmetic();

  expectedException.expect(IllegalArgumentException.class);
  expectedException.expectMessage("Division by zero is not supported");
  
  assumeTrue(false);

  obj1.divide(10, 0);

 }
}


When I ran ArithmeticTest.java, I observe that the test case is failed.




Previous                                                 Next                                                 Home

Junit: Rules


Rules are used to enhance the behavior of each test method in a test class.

Below table summarizes the different rules supported by junit.
Rule
Description
By using this, you can check that your code is throwing specific exception.
Continue test execution even after failure
Create Temporary folder
Time out for all unit tests
Get the test case name under execution
Initialize external resources
Rules applicable to static fields
Chain multiple rules




Previous                                                 Next                                                 Home

Junit: parameterized tests

Parameterized tests are used to repeat the same test against different input values.

For example, I written an application that compute the factorial of a number.
package com.sample.arithmetic;

public class Factorial {

 public int factorial(int num) throws Exception {
  if (num < 0) {
   throw new IllegalArgumentException("Factorial is not computed for negative numbers");
  }

  int result = 1;

  for (int i = 2; i <= num; i++) {
   result *= i;
  }

  return result;
 }
}

I would like to test the above application with below input-output combinations.

Input
Expected Output
0
1
1
1
5
120
10
3628800

I written the test application like below.


FactorialTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class FactorialTest {
 @Test
 public void factorial_0_1() throws Exception {
  Factorial factorial = new Factorial();

  long actual = factorial.factorial(0);
  long expected = 1;

  assertEquals(expected, actual);
 }

 @Test
 public void factorial_1_1() throws Exception {
  Factorial factorial = new Factorial();

  long actual = factorial.factorial(1);
  long expected = 1;

  assertEquals(expected, actual);
 }

 @Test
 public void factorial_5_120() throws Exception {
  Factorial factorial = new Factorial();

  int actual = factorial.factorial(5);
  int expected = 120;

  assertEquals(expected, actual);
 }

 @Test
 public void factorial_10_3628800() throws Exception {
  Factorial factorial = new Factorial();

  int actual = factorial.factorial(10);
  int expected = 3628800;

  assertEquals(expected, actual);
 }

}

As you observe above test class, all the test cases following the same pattern and leads to lot of redundant code.
a.   Calling the factorial function with some input
b.   Verifying the output with expected value.

By using parameterized test, you can remove this redundant code.

Step 1:  Create a parameterized test class.
@RunWith(Parameterized.class)
public class FactorialTest {


}


Step 2: Define input and expectedResult fields.

Step 3: Define a constructor that initializes input and expectedResult fields.

Step 4: Create a static method that generates and returns test data. Annotate the static method with ‘@parameterized.Parameters’ annotation.

Step 5: Now write the test case.
         @Test
         public void testFactorial() throws Exception {
                  int output = fact.factorial(input);
                  assertEquals(expectedResult, output);
         }

Find the below working example.

FactorialTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

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

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
@RunWith(Parameterized.class)
public class FactorialTest {
 private int input;
 private int expectedResult;

 private Factorial fact;

 @Before
 public void init() {
  fact = new Factorial();
 }

 @Parameterized.Parameters
 public static Iterable<Object[]> data() {
  return Arrays.asList(new Object[][] { { 0, 1 }, { 1, 1 }, { 5, 120 }, { 10, 3628800 } });
 }

 public FactorialTest(int input, int expectedResult) {
  this.input = input;
  this.expectedResult = expectedResult;
 }

 @Test
 public void testFactorial() throws Exception {
  int output = fact.factorial(input);
  assertEquals(expectedResult, output);
 }

}


When I ran the above application, it executes 4 test cases. I can able to see below kind of report.




Previous                                                 Next                                                 Home

Junit: @Ignore: Ignoring tests

There are situations, where you want to ignore some tests from execution. You can do that by adding @Ignore annotation on a test case. Junit test runners report the number of ignored test cases along with the number of tests that ran and the number of tests that failed.

@Ignore
@Test
public void factorial_10_3628800() throws Exception {
                 
}

You can even specify the reason, why you are ignoring the test case by passing the details to @Ignore annotation.

@Ignore("Smae kind of test is already written")
@Test
public void factorial_10_3628800() throws Exception {
                 
}

Find the below working example.

Factorial.java

package com.sample.arithmetic;

public class Factorial {

 public long factorial(int num) throws Exception {
  if (num < 0) {
   throw new IllegalArgumentException("Factorial is not computed for negative numbers");
  }

  if(num > 10) {
   throw new Exception("Can't calculate factorial for big number");
  }
  
  long result = 1;

  for (int i = 2; i <= num; i++) {
   result *= i;
  }

  return result;
 }
}

FactorialTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Ignore;
import org.junit.Test;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class FactorialTest {

 @Test
 public void factorial_5_120() throws Exception {
  Factorial factorial = new Factorial();

  long actual = factorial.factorial(5);
  long expected = 120;

  assertEquals(expected, actual);
 }

 @Ignore("Smae kind of test is already written")
 @Test
 public void factorial_10_3628800() throws Exception {
  Factorial factorial = new Factorial();

  long actual = factorial.factorial(10);
  long expected = 3628800;

  assertEquals(expected, actual);
 }
}


When you ran FactorialTest.java in eclipse, you can able to see below kind of report.


As you observe above report, it is clearly telling that 1 test out of 2 is skipped.


Previous                                                 Next                                                 Home

Sunday, 1 July 2018

Junit: Working with text fixtures @Before, @After, @BeforeClass, @AfterClass

Text fixtures are used to eliminate duplicate code.

Let me explain with an example.
public class CollectionsTest {

 private List<String> list;
 
 @Test
 public void collection_emptyTest() {
  list = new ArrayList<> ();
  assertEquals(list.size(), 0);
  list = null;
 }
 
 @Test
 public void collection_elementTest() {
  list = new ArrayList<> ();
  list.add("Hello");
  assertEquals(list.size(), 1);
  list = null;
 }
 
}

As you observe above example, below statements are repeated in both the test cases.
a.   list = new ArrayList<> ();     // Initialization task
b.   list = null;  // Cleanup task

We can get rid of this duplicated code using text fixtures @Before, @After.


CollectionTest.java
package com.sample.test;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class CollectionsTest {

 private List<String> list;

 @Before
 public void setUp() {
  list = new ArrayList<>();
 }

 @Test
 public void collection_emptyTest() {
  assertEquals(list.size(), 0);
  list = null;
 }

 @Test
 public void collection_elementTest() {
  list.add("Hello");
  assertEquals(list.size(), 1);

 }

 @After
 public void cleanUp() {
  list = null;
 }

}

@Before annotation
If you annotate any method with @Before annotation, then then that method runs before the every test case ('org.junit.Test' method). In case of inheritance, The @Before methods of super classes will be run before those of the current class, unless they are overridden in the current class. It is mainly used for initializing activities.

@After annotation
If you annotate any method with @After annotation, then then that method runs after the every test case ('org.junit.Test' method). It is mainly used for cleanup activities. In case of inheritance, the @After annotated methods declared in super classes will run after those of the current class, unless they are overridden in the current class.

In the above example, tests might execute in below order. The ordering of the tests execution is not guaranteed. so collection_elementTest () might be executed before collection_emptyTest().

setUp()
collection_emptyTest()
cleanUp()
setUp()
collection_elementTest()
cleanUp()


Apart from @Before, @After annotations, junit provides @BeforeClass, @AfterClass annotations, these will get executed once for all the testcases. Sometimes some tests need to share the common setup like data base connections, log files etc., In these kind of cases, you can place the initialization code in @BeforeClass annotated method and cleanup code in @AfterClass method.

Example
@BeforeClass
public static void init() {
         System.out.println("I am in init");
}
        
@AfterClass
public static void destroy() {
         System.out.println("\nI am in destroy");
}

Find the below working application.

TestApplicaiton.java
package com.sample.test;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestApplicaiton {

 @BeforeClass
 public static void init() {
  System.out.println("I am in init");
 }

 @Before
 public void setUp() {
  System.out.println("\nI am in setUp method");
 }

 @Test
 public void testCase1() {
  System.out.println("I am in testCase1");
 }

 @Test
 public void testCase2() {
  System.out.println("I am in testCase2");
 }

 @After
 public void cleanUp() {
  System.out.println("I am in cleanUp");
 }

 @AfterClass
 public static void destroy() {
  System.out.println("\nI am in destroy");
 }

}


When you ran TestApplication.java, you can able to see below messages in console.

I am in init

I am in setUp method
I am in testCase1
I am in cleanUp

I am in setUp method
I am in testCase2
I am in cleanUp

I am in destroy






Previous                                                 Next                                                 Home