Theories are less known components of Junit, but lately I used them and thus decided to write about them. They come in handy when you have a situation when you need to test a behavior with multiple input values. Instead of writing tests for each situation you can specify a set of inputs and apply them on the same test.
In order to use them a new runner called Theories must be added to the test.
@RunWith(Theories.class)
Then each input data must be annotated with the
@DataPoint
and finally the @Test annotation is replaced by the
@Theory
Let’s assume that for some reason we want to test that in a batch on countries in at least one a specific language is spoken. Then the test would look something like
@RunWith(Theories.class)
public class CountryTest {
private static final String GERMAN_USE_CASE = "german";
@DataPoint(GERMAN_USE_CASE)
public static List countryBatch1 = Arrays.asList(new Country("DE"), new Country("FR"), new Country("AT"), new Country("BE"));
@DataPoint(GERMAN_USE_CASE)
public static List countryBatch2 = Arrays.asList(new Country("DE"), new Country("EN"), new Country("IT"), new Country("SK"));
@DataPoint(GERMAN_USE_CASE)
public static List countryBatch3 = Arrays.asList(new Country("HU"), new Country("ES"), new Country("LUX"), new Country("AT"));
private List germanSpeakingCountries = Arrays.asList("DE", "AT", "CH");
@Theory
public void testGermanIsSpokenInAtLeastOneCountry(@FromDataPoints(GERMAN_USE_CASE) List countries) {
assertThat(countries).areAtLeastOne(buildGermanCondition(countries));
}
private Condition buildGermanCondition(List<Country> countries) {
Predicate predicate = country -> germanSpeakingCountries.contains(country.getLanguage());
return new Condition(predicate, "German speaking countries", countries);
}
}
Of course the @DataPoint annotation does not require a value, but in case you need to apply specific data points to specific theory, this is the way to do it. That’s pretty much it. It comes in handy when you need to test a combination of inputs and check a specific condition is met.
SOURCE CODE
Like this:
Like Loading...