@Theory and @DataPoint JUnit Annotations
Introduction
In this post, we will discuss @Theory and @DataPoint JUnit Annotations.
A Theory is a method that is executed against several data inputs called data points. To make a test method a theory we can mark it with @Theory annotation. In addition, to create a data point we need to create a public field in the test class and mark it with @DataPoint.
The Theories runner executes the method as many times as the number of data points declared, providing a different data point as the input argument on each invocation of the method.
We can specify the Theories runner as shown below:
@RunWith(Theories.class)
A Theory differs from standard test method in that it captures some aspect of the intended behavior in possibly
infinite numbers of scenarios which corresponds to the number of data points declared. Using assumptions and
assertions properly together with covering multiple scenarios with different data points can make your tests more
flexible.
Sample Code Snippet:
@RunWith(Theories.class) public class SimpleTest { @DataPoint public static String responseLine1 = "200 OK User Created"; @DataPoint public static String responseLine2 = "401 Unauthorized Not able to create"; @Theory public void validatingRestApiResponse(String response) { System.out.println("Validating REST Call:" + response); assumeThat(response, containsString("200")); assertThat(response, containsString("User Created")); } }
Run Output: Validating REST Call:200 OK User Created Validating REST Call:401 Unauthorized Not able to create
In the sample program, we have run the theory against 2 data points. One is valid and another one is invalid. However, we can notice that the theory has run for both the data points. If any of the assumptions fail, the data point is silently ignored. If all of the assumptions pass, but an assertion fails, the test itself fails.