Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

JUnit Theories with DataPoints

farenda 2016-01-11 0

JUnit Theories is advanced and experimental feature that allows to execute tests with selection of dynamically generated data. In this post we’re going to show how to provide input data using DataPoints.

To create a test a JUnit Theory we need a few things:

  • run the test class with org.junit.experimental.theories.Theories test runner
  • provide test data using DataPoints or ParameterSupplier
  • annotate test method with @Theory annotation!

Contrary to JUnit Parameterized tests Theories automatically produce Cartesian product of input data, which would be rather tedious in parameterized tests. Moreover, JUnit Theories allow to name @DataPoints and use them by their names, as can be seen in the first Theory.

In the following example we’ve got three @DataPoints methods:

  • named “a values” and “b values” that return integers
  • unnamed, that returns collection of strings.

DataPoints have to return iterables, so arrays, collections, etc. will do.

Also we define two Theories. The first one selects @DataPoints for their parameters (using @FromDataPoints annotation), whereas the second one matches correct @DataPoint by its parameter type:

package com.farenda.junit;

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

import java.util.Arrays;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeTrue;

@RunWith(Theories.class)
public class TheoriesAndDataPointsTest {

    @DataPoints("a values")
    public static int[] aValues() {
        // Use new Random().nextInt() to experiment:
        int[] ints = {1, 2};
        System.out.println("Generated test data: "
                + Arrays.toString(ints));
        return ints;
    }

    @DataPoints("b values")
    public static int[] bValues() {
        // Generate dynamically:
        int[] ints = {3, 4};
        System.out.println("Generated test data: "
                + Arrays.toString(ints));
        return ints;
    }

    @Theory
    public void sumShouldBeCommutative(@FromDataPoints("a values") int a,
                                       @FromDataPoints("b values") int b) {
        System.out.printf("a = %d, b = %d%n", a, b);
        assertEquals(a + b, b + a);
    }

    @DataPoints
    public static List<String> languages() {
        List<String> languages = asList("Java", null, "", "Groovy");
        System.out.println("Generated languages: " + languages);
        return languages;
    }

    @Theory(nullsAccepted = false)
    public void shouldMinValue(String language) {
        // This will filter out empty strings:
        assumeTrue("Language must be non empty!", language.length() > 0);
        System.out.printf("Asserting language: '%s'%n", language);
        assertThat(language, containsString("v"));
    }
}

Now, when you run the above code it will print the following results:

Generated test data: [1, 2]
Generated test data: [3, 4]
a = 1, b = 3
a = 1, b = 4
Generated test data: [3, 4]
a = 2, b = 3
a = 2, b = 4
Generated languages: [Java, null, , Groovy]
Asserting language: 'Java'
Asserting language: 'Groovy'

As you can see in the first Theory all combinations of a’s and b’s have been passed as parameters. Keep in mind that methods that return @DataPoints may be called multiple times as @DataPoints(“b values”) in this example.
In the second theory, we are not specifying Theory DataPoints, but let JUnit Theories runner to match them by type of parameter. This way it grabs @DataPoints from method returning collection of strings and calls the Theory with each value as parameter. Note that we specified @Theory(nullsAccepted = false) to remove nulls from input data. Also we’re using JUnit Assume to execute assertions only when provided data meets preconditions.

How pros do it

This time no pro code, because we couldn’t find any. If you know application of JUnit Theories in the wild just let us know!

Share with the World!
Categories JUnit Tags java, junit, unit-tests
Previous: JUnit Custom Rules
Next: JUnit Theories with built-in ParamaterSuppliers

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok