Sunday 15 August 2021

Junit5: TestInfo: Get information about the test

TestInfo class is used to inject information about the current test or container into a @Test, @RepeatedTest, @ParameterizedTest,  @TestFactory, @BeforeEach, @AfterEach, @BeforeAll, and @AfterAll methods.

 

If a constructor or method parameter is of type TestInfo, the TestInfoParameterResolver will supply an instance of TestInfo corresponding to the current container or test as the value for the parameter.

 

Using TestInfo instance, you can retrieve information about the current container or test such as the display name, the test class, the test method, and associated tags

 

TestInfoDemo.java

package com.sample.app;

import java.util.Set;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

public class TestInfoDemo {

	public TestInfoDemo(TestInfo testInfo) {
		System.out.println("\nInside Constructor");
		String displayName = testInfo.getDisplayName();
		System.out.println("\t" + displayName);
	}

	@BeforeEach
	void init(TestInfo testInfo) {
		System.out.println("\nInside init method");
		String displayName = testInfo.getDisplayName();
		System.out.println("\t" + displayName);
	}

	@Test
	@DisplayName("TEST 1")
	@Tag("demoTest")
	@Tag("helloworld")
	void test1(TestInfo testInfo) {
		System.out.println("\nInside test1 method");

		String displayName = testInfo.getDisplayName();
		Set<String> tags = testInfo.getTags();

		System.out.println("\t" + displayName);
		System.out.println("\t" + tags);

	}

	@Test
	void test2() {
		System.out.println("\nInside test2 method");
	}
}

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment