Skip to content

@DataProducer

Serge Bishyr edited this page Apr 20, 2017 · 2 revisions

Provides lazy calculated parameters inserted to test method.

Example

Simple example

The value of stringProducer will be calculated and injected to the testMethod(String string)

@DataProducer
public static Supplier<String> stringProducer = () -> RandomStringProvider.get();

@Test
public void testMethod(String string) {
   ...
}

Example with iterations

The testMethod(String string) will run three times (@ProducedValues(iterations = 3)). Each run the value of stringProducer will be recalculated, so the new value will be provided.

@DataProducer
public static Supplier<String> stringProducer = () -> RandomStringProvider.get();

@Test
@ProducedValues(iterations = 3)
public void testMethod(String string) {
   ...
}

Named @DataProducer

To testMethod(@ProducedValue(producer = "calculated") String string) will be injected values from calculatedProducer. If no name is specified for @DataProducer, the field name will be considered as @DataProducer name.

@DataProducer
public static Supplier<String> randomProducer = () -> RandomStringProvider.get();

@DataProducer(name = "calculated")
public static Supplier<String> calculatedProducer = () -> CalculatedStringProvider.get();

@Test
public void testMethod(@ProducedValue(producer = "calculated") String string) {
   ...
}

Multiple @DataProducer of the same type

Method test(String s) will be executed twice. The first time value from random @DataProducer will be injected. The second time value from queue @DataProducer will be injected.

@DataProducer
public static Supplier<String> random = () -> RandomStringProvider.get();

@DataProducer
public static Supplier<String> queue = () -> StringQueue.next();
 
@Test
public void test(String s) {
    ...
}

Multiple @DataProducer of the same type and iterations

Method test(String s) will be executed six times. Three iterations with each @DataProducer.

@DataProducer
public static Supplier<String> random = () -> RandomStringProvider.get();

@DataProducer
public static Supplier<String> queue = () -> StringQueue.next();

@Test
@ProducedValues(iterations = 3)
public void test(String s) {
    ...
}

Method as @DataProducer

Public static method with return type Collection<Supplier<T>> can be annotated with @DataProducer

@DataProducer
public static List<Supplier<String>> dataProducer() {
    return Arrays.asList(
        () -> "return",
        () -> "42"
    );
}

The following example is equivalent to having two @DataProducer fields of the same type.