JUnit Tutorial
Introduction to Junit JUnit Set up JUnit Architecture JUnit Annotations JUnit Fixtures Junit Assertions Junit Categories @Test Annotation Parameters Verification of Exceptions Ignoring tests Time out in JUnit tests Parameterizing tests Test Suite TestWatcher TemporaryFolder ExternalResource Theories in JUnit JUnit Test Runners Execution order of JUnit tests Assumptions in JUnit JUnit and Hamcrest Matchers Running JUnit tests in parallel JUnit and Maven Integration JUnit and Gradle Integration Executing Selenium tests using JUnit test framework Method interceptor and usage JUnit in Intellij IDEA JUnit in EclipseTheories 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!!