Theories in junit

Junit Theories allow you to test theories with all possible combinations of data points. For example – Consider below mathematical expression.
 
a+b > a and a+b > b where a,b > 0

Above expressions are always true for all combination of values of a and b. To test above theory, we can write a simple test and verify it. But To test above expressions with many data points, we will have to write more code. But JUnit theories can test many data points very easily. Below example explains how we can use Theories in JUnit to verify below theories.
 
(a+b)^2 = a^2 + b^2 + 2*a*b
a+b > a, a+b > b where a, b > 0

 
package theories;

import org.junit.Assume;
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.assertEquals;
import static org.junit.Assert.assertTrue;

@RunWith(Theories.class)
public class MyJunitTheories {

    @DataPoints
    public static int[] dataPoints() {
        return new int[]{
                71, 82, 53,-1
        };
    }

    //For a and b where a,b > 0
    //(a+b)^2 = a^2+b^2+2ab
    //a+b > a and a+b > b
    @Theory
    public void squareTheory(Integer a, Integer b) {
        //Below assume statement ensures that we are testing only positive numbers
        Assume.assumeTrue(a > 0 && b > 0);

        System.out.println("Running with Data points - " + a + " , "+ b);

        Double leftSide = Math.pow(a+b,2);
        Double rightSide = Double.valueOf(a * a + b * b + 2 * a * b);

        assertEquals(leftSide,rightSide);
        assertTrue(a + b > a);
        assertTrue(a + b > b);
    }

}

Here is the output of above code.
 
Running with Data points – 71 , 71
Running with Data points – 71 , 82
Running with Data points – 71 , 53
Running with Data points – 82 , 71
Running with Data points – 82 , 82
Running with Data points – 82 , 53
Running with Data points – 53 , 71
Running with Data points – 53 , 82
Running with Data points – 53 , 53 

Web development and Automation testing

solutions delivered!!