Monday 23 August 2021

Junit5: Generate dynamic tests using DynamicContainer

A DynamicContainer is a container generated at runtime. It is composed of a display name and an Iterable or Stream DynamicNodes.

 

Instances of DynamicContainer must be generated by factory methods annotated with @TestFactory annotation.

@API(status = MAINTAINED, since = "5.3")
public class DynamicContainer extends DynamicNode {

	public static DynamicContainer dynamicContainer(String displayName, Iterable<? extends DynamicNode> dynamicNodes) {
		return dynamicContainer(displayName, null, StreamSupport.stream(dynamicNodes.spliterator(), false));
	}

	public static DynamicContainer dynamicContainer(String displayName, Stream<? extends DynamicNode> dynamicNodes) {
		return dynamicContainer(displayName, null, dynamicNodes);
	}

	public static DynamicContainer dynamicContainer(String displayName, URI testSourceUri,
			Stream<? extends DynamicNode> dynamicNodes) {

		return new DynamicContainer(displayName, testSourceUri, dynamicNodes);
	}


}

Find the below working application.

 

DynamicContainerDemo1.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;

import java.util.stream.Stream;

import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.TestFactory;

public class DynamicContainerDemo1 {
	@TestFactory
	Stream<DynamicNode> dynamicTestsWithContainers() {
		return Stream
				.of("Hello")
				.map(input -> dynamicContainer("Container " + input,
						Stream.of(dynamicTest("not null", () -> assertNotNull(input)),
								dynamicContainer("properties",Stream.of(
										dynamicTest("length > 0", () -> assertTrue(input.length() > 0)),
										dynamicTest("not empty", () -> assertFalse(input.isEmpty())))),
										dynamicContainer("utilities", Stream.of(
												dynamicTest("string reversal", () -> assertEquals("olleH", reverse(input))))))));
	}

	private static String reverse(String str) {
		return new StringBuilder().append(str).reverse().toString();
	}
}


Run above application, you will see the test results in junit window.





 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment