Saturday, 7 July 2018

Junit: Theories

Theories are most powerful assertions, used to state our assumptions clearly.

Let me try to explain with an example,

A typical mathematical theory looks like below.
For every integer a and b, a + b = b + a is always true.

Since, integers are infinite, you can’t test for infinite number of integers. You may test the above theory with some sample data.

For example, for the below sample data, you will end up in testing 36 (Since there are 6 numbers, total combination = 6 * 6 = 36) combinations
-7, 9, 0, -8, 19, 4

TestApp.java
package com.sample.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TestApp {

 @Test
 public void aPlusBIsCumulative() {
  assertTrue((-7 + -7) == (-7 + -7));
  assertTrue((-7 + 9) == (9 + -7));
  assertTrue((-7 + 0) == (0 + -7));
  assertTrue((-7 + -8) == (-8 + -7));
  assertTrue((-7 + 19) == (19 + -7));
  assertTrue((-7 + 4) == (4 + -7));
  assertTrue((9 + -7) == (-7 + 9));
  assertTrue((9 + 9) == (9 + 9));
  assertTrue((9 + 0) == (0 + 9));
  assertTrue((9 + -8) == (-8 + 9));
  assertTrue((9 + 19) == (19 + 9));
  assertTrue((9 + 4) == (4 + 9));
  assertTrue((0 + -7) == (-7 + 0));
  assertTrue((0 + 9) == (9 + 0));
  assertTrue((0 + 0) == (0 + 0));
  assertTrue((0 + -8) == (-8 + 0));
  assertTrue((0 + 19) == (19 + 0));
  assertTrue((0 + 4) == (4 + 0));
  assertTrue((-8 + -7) == (-7 + -8));
  assertTrue((-8 + 9) == (9 + -8));
  assertTrue((-8 + 0) == (0 + -8));
  assertTrue((-8 + -8) == (-8 + -8));
  assertTrue((-8 + 19) == (19 + -8));
  assertTrue((-8 + 4) == (4 + -8));
  assertTrue((19 + -7) == (-7 + 19));
  assertTrue((19 + 9) == (9 + 19));
  assertTrue((19 + 0) == (0 + 19));
  assertTrue((19 + -8) == (-8 + 19));
  assertTrue((19 + 19) == (19 + 19));
  assertTrue((19 + 4) == (4 + 19));
  assertTrue((4 + -7) == (-7 + 4));
  assertTrue((4 + 9) == (9 + 4));
  assertTrue((4 + 0) == (0 + 4));
  assertTrue((4 + -8) == (-8 + 4));
  assertTrue((4 + 19) == (19 + 4));
  assertTrue((4 + 4) == (4 + 4));

 }

}


What if you want to test for 100 samples, you will end up in writing 100 * 100 assert statements (or) you yourself code the logic like below.

TestApp.java
package com.sample.test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class TestApp {

 private static int[] data = { -7, 9, 0, -8, 19, 4 };

 @Test
 public void aPlusBIsCumulative() {
  for (int i : data) {
   for (int j : data) {
    assertEquals((i + j), (j + i));
   }
  }

 }

}


Instead of writing all the testing logic, junit theories helps you to test above kind of scenarios in easy way.
package com.sample.test;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertTrue;

@RunWith(Theories.class)
public class TestApp {

 @DataPoints
 public static int[] integers() {
  return new int[] { -7, 9, 0, -8, 19, 4 };
 }

 @Theory
 public void aPlusBIsCumulative(Integer a, Integer b) {
  assertTrue((a + b) == (b + a));
 }

}

@DataPoints
When you annotate an array or iterable-typed field or method with @DataPoints annotation, then it will cause the values in the array or iterable given to be used as parameters for theories in that class when run with the Theories runner.

@Theory
If you mark any test method with @Theory annotation, then that test method should be read as theories by the 'org.junit.experimental.theories.Theories' runner.

Example 2: for any non-null string s, s = reverse(reverse(s))

TestApp.java
package com.sample.test;

import static org.junit.Assert.assertEquals;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

@RunWith(Theories.class)
public class TestApp {

 private static String reverse(String s) {
  String reverse = "";

  for (int i = s.length() - 1; i >= 0; i--) {
   reverse = reverse + s.charAt(i);
  }
  return reverse;
 }

 @DataPoints
 public static String input[] = {"Hello", "How", "Are", "You"};

 @Theory
 public void strReverseTwice(String s) {
  assertEquals(s, reverse(reverse(s)));
 }

}







Previous                                                 Next                                                 Home

Junit: Ordering test cases execution

By default, junit do not specify the execution order of the test cases (Order of execution depends on the order returned by the reflection API).

Junit provides '@FixMethodOrder' annotation, to order the execution of test cases.

Example
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestApp {

}

In the above example, test cases in TestApp class will execute in lexicographic order.

MethodSorters is an enumerator, provides below constants.

NAME_ASCENDING: Sorts the test methods by the method name, in lexicographic order.
JVM: Execute test methods in the order returned by the JVM.
DEFAULT: Sorts the test methods in a deterministic, but not predictable, order

When I check the code, the default method sorter is implemented like below.

 public static final Comparator<Method> DEFAULT = new Comparator<Method>() {
        public int compare(Method m1, Method m2) {
            int i1 = m1.getName().hashCode();
            int i2 = m2.getName().hashCode();
            if (i1 != i2) {
                return i1 < i2 ? -1 : 1;
            }
            return NAME_ASCENDING.compare(m1, m2);
        }
    };

Find the below working application.

TestApp.java
package com.sample.test;

import static org.junit.Assert.assertTrue;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestApp {

 @Test
 public void testCase3() {
  System.out.println("Executing test case 3");
  assertTrue(true);
 }

 @Test
 public void testCase2() {
  System.out.println("Executing test case 2");
  assertTrue(true);
 }

 @Test
 public void testCase4() {
  System.out.println("Executing test case 4");
  assertTrue(true);
 }

 @Test
 public void testCase1() {
  System.out.println("Executing test case 1");
  assertTrue(true);
 }

 @Test
 public void testCase5() {
  System.out.println("Executing test case 5");
  assertTrue(true);
 }

}

When you ran above class, you can able to see below messages in the console.

Executing test case 1
Executing test case 2
Executing test case 3
Executing test case 4
Executing test case 5





Previous                                                 Next                                                 Home

Junit: @RuleChain: Ordering junit rules

By using RuleChain, we can execute the test rules in specific order.

Example



In the above esample, CustomLogger rule is executed first followed by TestCaseExecutionTimer rule.

Find the below working application.

CustomLogger.java
package com.sample.customrules;

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

public class CustomLogger implements TestRule {

 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    System.out.println("Executing : " + description.getMethodName());
    base.evaluate();
    System.out.println("Execution done for : " + description.getMethodName());
   }
  };
 }

}

TestCaseExecutionTimer.java

package com.sample.customrules;

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

public class TestCaseExecutionTimer implements TestRule {
 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    long time1 = System.currentTimeMillis();
    base.evaluate();
    long time2 = System.currentTimeMillis();

    if (description.getMethodName() != null) {
     System.out.println(description.getMethodName() + " takes " + (time2 - time1) + " milliseconds");
    } else {
     System.out.println("Test cases in " + description.getClassName() + " takes " + (time2 - time1)
       + " milliseconds");
    }

   }
  };
 }
}

TestApp.java

package com.sample.test;

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

import com.sample.customrules.CustomLogger;
import com.sample.customrules.TestCaseExecutionTimer;

public class TestApp {
 @Rule
 public RuleChain chain = RuleChain.
       outerRule(new CustomLogger()).
       around(new TestCaseExecutionTimer());

 @Test
 public void testCase1() throws InterruptedException {
  Thread.sleep(500);
 }

 @Test
 public void testCase2() throws InterruptedException {
  Thread.sleep(100);
 }

}


Run TestApp.java, you can able to see below messages in console.

Executing : testCase1
testCase1 takes 503 milliseconds
Execution done for : testCase1
Executing : testCase2
testCase2 takes 101 milliseconds
Execution done for : testCase2


Previous                                                 Next                                                 Home

Friday, 6 July 2018

Junit: @ClassRule annotation

It is like @Rule annotation, only difference is, this rule only applicable to static fields, methods.


For example, below example calculates the execution time of all the test cases.


TestCaseExecutionTimer.java
package com.sample.customrules;

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

public class TestCaseExecutionTimer implements TestRule{
 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    long time1 = System.currentTimeMillis();
    base.evaluate();
    long time2 = System.currentTimeMillis();
    
    System.out.println("Test cases in " + description.getClassName() + " takes " + (time2-time1) + " milliseconds");
   }
  };
 }
}

TestApp.java
package com.sample.test;

import org.junit.ClassRule;
import org.junit.Test;

import com.sample.customrules.TestCaseExecutionTimer;

public class TestApp {
 @ClassRule
 public static TestCaseExecutionTimer timer = new TestCaseExecutionTimer();

 @Test
 public void testCase1() throws InterruptedException {
  System.out.println("Executing testCase1");
  Thread.sleep(500);
 }

 @Test
 public void testCase2() throws InterruptedException {
  System.out.println("Executing testCase2");
  Thread.sleep(100);
 }

}


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

Executing testCase1
Executing testCase2
Test cases in com.sample.test.TestApp takes 609 milliseconds

Now let’s combine both @Rule and @ClassRule to get each test case execution time and cumulative execution time.

TestCaseExecutionTimer.java

package com.sample.customrules;

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

public class TestCaseExecutionTimer implements TestRule {
 @Override
 public Statement apply(Statement base, Description description) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    long time1 = System.currentTimeMillis();
    base.evaluate();
    long time2 = System.currentTimeMillis();

    if (description.getMethodName() != null) {
     System.out.println(description.getMethodName() + " takes " + (time2 - time1) + " milliseconds");
    } else {
     System.out.println("Test cases in " + description.getClassName() + " takes " + (time2 - time1)
       + " milliseconds");
    }

   }
  };
 }
}

TestApp.java

package com.sample.test;

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

import com.sample.customrules.TestCaseExecutionTimer;

public class TestApp {
 @ClassRule
 public static TestCaseExecutionTimer CumulativeTimer = new TestCaseExecutionTimer();

 @Rule
 public TestCaseExecutionTimer testCaseTimer = new TestCaseExecutionTimer();
 
 @Test
 public void testCase1() throws InterruptedException {
  System.out.println("Executing testCase1");
  Thread.sleep(500);
 }

 @Test
 public void testCase2() throws InterruptedException {
  System.out.println("Executing testCase2");
  Thread.sleep(100);
 }

}


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

Executing testCase1
testCase1 takes 501 milliseconds
Executing testCase2
testCase2 takes 100 milliseconds
Test cases in com.sample.test.TestApp takes 606 milliseconds








Previous                                                 Next                                                 Home