Monday 9 August 2021

Junit5: Dependency injection for constructors and methods

In Junit Jupiter, you can use parameterized constructors and methods.

'org.junit.jupiter.api.extension.ParameterResolver' interface is used to dynamically resolve parameters at run time.

 

There are three built-in resolvers available to dynamically resolve parameters at run time.

 

a.   TestInfoParameterResolver

b.   RepetitionInfoParameterResolver

c.    TestReporterParameterResolver

 

TestInfoParameterResolver

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.

 

TestInfoParameterResolverDemo.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 TestInfoParameterResolverDemo {

	public TestInfoParameterResolverDemo(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");
	}

}

 

Run above class, you will see below messages in console.

Inside Constructor
	TestInfoParameterResolverDemo

Inside init method
	TEST 1

Inside test1 method
	TEST 1
	[demoTest, helloworld]

Inside Constructor
	TestInfoParameterResolverDemo

Inside init method
	test2()

Inside test2 method

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment