Dependency Injection and Testing in JUnit 5

By | October 3, 2020

In this post, We will talk and learn about Dependency Injection for Constructors and Methods

In all previous JUnit versions, test constructors or methods were not allowed to have parameters. We have one of the major changes in JUnit Jupiter, both test constructors and methods are now permitted to have parameters. These allow for greater flexibility and enable Dependency Injection for constructors and methods.

In case if a test class method or constructor, or a lifecycle method accepts TestInfo as a parameter then the parameter must be resolved at runtime by automatically registered ParameterResolver.

We can use TestInfo to retrieve information about the current container or test such as the display name, the test class, the test method, and associated tags.

Let’s try to understand the above concept using a demo project:

pom.xml

 

MyUtils.java

 

DIForConstructorAndMethodTest.java

The output of the above project:

You May Also Like:

Junit 5 Architecture
JUnit 5 Annotations
JUnit 5 Maven Dependency
JUnit 5 with Gradle Dependency
JUnit 5 Test Lifecycle
JUnit 5 @BeforeAll annotation example
Unit 5 @AfterAll annotation example
JUnit 5 @BeforeEach and @AfterEach annotation Example
JUnit 5 Display Names
Assertions in JUnit 5 Examples
Third-party Assertion Libraries support in JUnit 5
JUnit 5 Assumptions Examples
Conditional Test Execution in JUnit 5
JUnit 5 Nested Tests Example
JUnit 5 @Tag Annotation example
Test Execution Order in Junit 5

That’s all about Dependency Injection and Testing in JUnit 5
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *