Saturday, 30 June 2018

Junit: categorising test cases

By using @Category annotation, you can place the test case (or) complete test class under specific categories.

Example 1: Placing complete test class under FastTest, ArithmeticCalculationsTest.

For example, I placed ArithmeticTest class under FastTest, ArithmeticCalculationsTest categories.

@Category({FastTest.class, ArithmeticCalculationsTest.class})
public class ArithmeticTest {

         .....
         .....

}


Example 2: Pacing the method 'factorial_5_120' under FastTest category.
         @Test
         @Category(FastTest.class)
         public void factorial_5_120() throws Exception {
                  Factorial factorial = new Factorial();

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

                  assertEquals(expected, actual);
         }

You can execute the test cases under given category like below.

@RunWith(Categories.class)
@IncludeCategory({ ArithmeticCalculationsTest.class })
@ExcludeCategory(FastTest.class)
@SuiteClasses({ ArithmeticTest.class, FactorialTest.class, FibonacciTest.class })
public class ArithmeticTestSuite {

}

‘ArithmeticTestSuite’ class execute the tests in ArithmeticTest, FactorialTest classes by including ‘ArithmeticCalculationsTest’ category and excluding FastTest category.

@RunWith(Categories.class)
@IncludeCategory({ FastTest.class })
@SuiteClasses({ ArithmeticTest.class, FactorialTest.class, FibonacciTest.class })
public class FastTestSuite {

}

‘FastTestSuite’ class execute the ‘FastTest’ category tests in ArithmeticTest.class, FactorialTest.class, FibonacciTest.class.

Find the below working application.

Arithmetic.java

package com.sample.arithmetic;

public class Arithmetic {

 public int sum(int a, int b) {
  return a + b;
 }
 
}

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;
 }
}

Fibonacci.java

package com.sample.arithmetic;

public class Fibonacci {

 public int fibNumber(int n) {
  if (n < 0)
   throw new IllegalArgumentException("Can't calculate fiboaaci for negative numbers");
  return fib(n);

 }

 private int fib(int n) {
  if (n == 1 || n == 0)
   return 1;
  return fib(n - 1) + fib(n - 2);
 }

}

ArithmeticTest.java

package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.sample.categories.ArithmeticCalculationsTest;
import com.sample.categories.FastTest;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
@Category({FastTest.class, ArithmeticCalculationsTest.class})
public class ArithmeticTest {

 private Arithmetic arithmetic = new Arithmetic();

 @Test
 public void add_10And5_15() {

  int expected = 15;
  int actual = arithmetic.sum(10, 5);

  assertEquals(expected, actual);
 }

 @Test
 public void add_10AndMinus5_5() {

  int expected = 5;
  int actual = arithmetic.sum(10, -5);

  assertEquals(expected, actual);
 }
}


FactorialTest.java

package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.sample.categories.ArithmeticCalculationsTest;
import com.sample.categories.FastTest;
import com.sample.categories.SlowTest;

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

 @Test
 @Category(FastTest.class)
 public void factorial_5_120() throws Exception {
  Factorial factorial = new Factorial();

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

  assertEquals(expected, actual);
 }

 @Test
 @Category(SlowTest.class)
 public void factorial_10_3628800() throws Exception {
  Factorial factorial = new Factorial();

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

  assertEquals(expected, actual);
 }
}

FibonacciTest.java

package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.sample.categories.ArithmeticCalculationsTest;
import com.sample.categories.FastTest;
import com.sample.categories.SlowTest;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
@Category(ArithmeticCalculationsTest.class)
public class FibonacciTest {

 @Test
 @Category(SlowTest.class)
 public void fibonacci_7_21() {
  Fibonacci fib = new Fibonacci();
  int actual = fib.fibNumber(7);
  int expected = 21;

  assertEquals(expected, actual);

 }

 @Test
 @Category(FastTest.class)
 public void fibonacci_38_2971215073() {
  Fibonacci fib = new Fibonacci();
  int actual = fib.fibNumber(38);
  int expected = 63245986;

  assertEquals(expected, actual);
 }
}


Categories are defined like below.

ArithmeticCalculationsTest.java

package com.sample.categories;

public interface ArithmeticCalculationsTest {

}

FastTest.java

package com.sample.categories;

public interface FastTest {

}

SlowTest.java

package com.sample.categories;

public interface SlowTest {

}


Test suites are defined like below.

ArithmeticTestSuite.java

package com.sample.testsuites;

import org.junit.experimental.categories.Categories;
import org.junit.experimental.categories.Categories.ExcludeCategory;
import org.junit.experimental.categories.Categories.IncludeCategory;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;

import com.sample.arithmetic.ArithmeticTest;
import com.sample.arithmetic.FactorialTest;
import com.sample.arithmetic.FibonacciTest;
import com.sample.categories.ArithmeticCalculationsTest;
import com.sample.categories.FastTest;

@RunWith(Categories.class)
@IncludeCategory({ ArithmeticCalculationsTest.class })
@ExcludeCategory(FastTest.class)
@SuiteClasses({ ArithmeticTest.class, FactorialTest.class, FibonacciTest.class })
public class ArithmeticTestSuite {

}

FastTestSuite.java

package com.sample.testsuites;

import org.junit.experimental.categories.Categories;
import org.junit.experimental.categories.Categories.IncludeCategory;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;

import com.sample.arithmetic.ArithmeticTest;
import com.sample.arithmetic.FactorialTest;
import com.sample.arithmetic.FibonacciTest;
import com.sample.categories.FastTest;

@RunWith(Categories.class)
@IncludeCategory({ FastTest.class })
@SuiteClasses({ ArithmeticTest.class, FactorialTest.class, FibonacciTest.class })
public class FastTestSuite {

}


Project structure looks like below.


When you ran ArithmeticTestSuite, below methods will get executed.


When you ran 'FastTestSuite', below methods will get executed.




Previous                                                 Next                                                 Home

Junit: Assumptions

Assumptions are very useful feature in junit. By using assumption, you can make sure that the test will not execute, if the preconditions/assumptions are not met. That means, the tests that do not satisfy the assumptions are skipped.

For example, below test case will execute in windows systems and skipped in other operating systems.

         @Test
         public void testCase1() {
                  assumeTrue(isWindows());
                  assertTrue("TestCase1 executed successfully", true);
         }

Find the below working application.

DemoTestApp.java
package com.sample.arithmetic;

import org.junit.Test;

import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
public class DemoTestApp {

 private static boolean isWindows() {
  String osType = System.getProperty("os.name");
  if (osType.contains("windows") || osType.contains("Windows") || osType.contains("WINDOWS")) {
   return true;
  }
  return false;
 }

 @Test
 public void testCase1() {
  assumeTrue(isWindows());
  assertTrue("TestCase1 executed successfully", true);
 }

 @Test
 public void testCase2() {
  assumeTrue(!isWindows());
  assertTrue("TestCase2 executed successfully", true);
 }

}

When I ran the tests in eclipse, I observed the testCase2 is skipped and it throws AssumptionViolatedException.

org.junit.Assume clas provides below methods to support different assumptions.


public static void assumeTrue(boolean b)
The test will be ignored, if the value of argument 'b' is false. When 'b' is false, junit throws AssumptionViolatedException.

public static void assumeTrue(String message, boolean b)
The test will be ignored, if the value of argument 'b' is false. When 'b' is false, junit throws AssumptionViolatedException with given message.

public static void assumeFalse(boolean b)
The test will be ignored, if the value of argument 'b' is true. When 'b' is false, junit throws AssumptionViolatedException.

public static void assumeFalse(String message, boolean b)
The test will be ignored, if the value of argument 'b' is true. When 'b' is false, junit throws AssumptionViolatedException with given message.

public static void assumeNotNull(Object... objects)
All the objects must not be null. If any of the objects is null, then the test is skipped and junit throws AssumptionViolatedException.

public static <T> void assumeThat(T actual, Matcher<T> matcher)
If the arguments 'actual' is not matched to the given matcher, then the test is skipped and junit throws AssumptionViolatedException.

public static <T> void assumeThat(String message, T actual, Matcher<T> matcher)
If the arguments 'actual' is not matched to the given matcher, then the test is skipped and junit throws AssumptionViolatedException with given message.

public static void assumeNoException(Throwable e)
It skips the tests on error cases, by throwing AssumptionViolatedException.

public static void assumeNoException(String message, Throwable e)
It skip the tests on error cases,  by throwing AssumptionViolatedException with given message.

Example of assumeNoException
In the below example, junit skip the test, if any exception is thrown by factorial() method.

         @Test
         public void testFactorial_12() {
                  Factorial fact = new Factorial();
                  long actual = -1;
                 
                  try {
                           actual = fact.factorial(12);
                  } catch (Exception e) {
                           assumeNoException(e);
                  }
                 
                  long expected = 479001600;
                 
                  assertEquals("Factorial of the number is not matched", expected, actual);
                 
         }

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.smaple.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeNoException;

import org.junit.Test;

import com.sample.arithmetic.Factorial;

public class FactorialTest {

 @Test
 public void testFactorial_5() {
  Factorial fact = new Factorial();
  long actual = -1;

  try {
   actual = fact.factorial(5);
  } catch (Exception e) {
   assumeNoException(e);
  }

  long expected = 120;

  assertEquals("Factorial of the number is not matched", expected, actual);

 }

 @Test
 public void testFactorial_12() {
  Factorial fact = new Factorial();
  long actual = -1;

  try {
   actual = fact.factorial(12);
  } catch (Exception e) {
   assumeNoException(e);
  }

  long expected = 479001600;

  assertEquals("Factorial of the number is not matched", expected, actual);

 }
}

When you ran FactorialTest.java, you can observe the test case ‘testFactorial_12’ is skipped.




Previous                                                 Next                                                 Home

Junit: Assert by matcher

Junit provides below methods to match the object with given matcher. Junit uses hamcrest library to perform comparison operations using matchers.

public static <T> void assertThat(T actual, Matcher<? super T> matcher)
Asserts that 'actual' satisfies the condition specified by matcher. If 'actual' is not satisifes the condition specified by matcher, then junit throws an assertion error without message.
          
public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher)
Asserts that 'actual' satisfies the condition specified by matcher. If 'actual' is not satisifes the condition specified by matcher, then junit throws an assertion error with message.

If you are interested in learning hamcrest, I would recommend you to go through my below tutorial series.

Example
String name = "Hello World";
assertThat(name, both(startsWith("Hello")).and(containsString("rld")));

Above example pass the test case, if the string ‘name’ starts with ‘Hello’ and contains the string ‘rld’.

Find the below working application.

DemoTestApp.java
package com.sample.arithmetic;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class DemoTestApp {

 @Test
 public void testAssertThatStringContainsBoth() {
  String name = "Hello World";
  assertThat(name, both(startsWith("Hello")).and(containsString("rld")));
 }

 @Test
 public void testAssertThatEitherOfString() {
  String name = "Hello World";
  assertThat(name, either(startsWith("Hello")).or(containsString("abrakadabra")));
 }

 @Test
 public void testAssertThatMatchAny() {
  String name = "Hello World";
  assertThat(name, anyOf(startsWith("Hello"), containsString("abrakadabra")));
 }

 @Test
 public void testAssertThatMatchEveryItem() {
  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("elements shoudl start with me", strs, everyItem(startsWith("me")));
 }

 @Test
 public void testAssertThatHasItems() {
  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("strs must have 'melt' and 'men'", strs, hasItems("melt", "men"));
 }

 @Test
 public void testAssertThatAllOf() {
  String name = "Hello World";

  assertThat(name, allOf(startsWith("Hello"), containsString("rld"), endsWith("World")));
 }
}




Previous                                                 Next                                                 Home