DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why Testing is a Long-Term Investment for Software Engineers
  • JUnit, 4, 5, Jupiter, Vintage
  • Readability in the Test: Exploring the JUnitParams
  • Creating Your Swiss Army Knife on Java Test Stack

Trending

  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Overcoming React Development Hurdles: A Guide for Developers
  • Why We Still Struggle With Manual Test Execution in 2025
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. JUnit 5: Injection Enabled Tests

JUnit 5: Injection Enabled Tests

Learn how to enable dependency injection in your test methods in JUnit's new release, JUnit 5.

By 
Mehdi Cheracher user avatar
Mehdi Cheracher
·
Nov. 14, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
34.5K Views

Join the DZone community and get the full member experience.

Join For Free

We all are excited about the new release of JUnit and are happy about the modularization of the platform and removing the restrictions that last version (JUnit 4) enforced (test methods must be public and have no arguments, test classes must be public, etc.).

Today I’ll try and explain how to enable dependency injection in your test methods, say for testing services when you don’t want to write a @BeforeAll each time you write a test to initialize them.

This is how our end result will look:

class TestClass {

  @Test
  @DisplayName("DemoService should be injected in the method params")
  void testMethod(DemoService service) {
    // do some work with the service
  }
}

The idea of dependency injection inside our tests is not something new; it is afforded by spring’s test utilities and it’s not that hard to implement for your general case. The following code snippet will show how you can create a custom JUnit 4 Runner to enable field injection inside your tests.

import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

/**
 * @author chermehdi
 */
public class InjectionRunner extends BlockJUnit4ClassRunner {

  private SeContainer container;

  /**
   * Creates a BlockJUnit4ClassRunner to run {@code klass}
   *
   * @throws InitializationError if the test class is malformed.
   */
  public InjectionRunner(Class<?> klass) throws InitializationError {
    super(klass);
    SeContainerInitializer initializer = SeContainerInitializer.newInstance();
    container = initializer.initialize();
  }

  /**
   * inject the dependencies of the given object
   */
  @Override
  protected Object createTest() throws Exception {
    Object test = super.createTest();
    return container.select(test.getClass()).get();
  }
}

The implementation uses CDI to do the injection but that’s just an implementation detail.

In your test class, you can just do this:

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author chermehdi
 */
@RunWith(InjectionRunner.class)
public class TestUsingRunner {

  @Inject
  SomeService service;

  @Inject
  SomeOtherService serviceOther;

  @Test
  public void helloTest() {
    assertEquals("i am a service depend", service.getString());
  }

  @Test
  public void helloTestAgain() {
    assertEquals("i am a service", serviceOther.getString());
  }
}

This was the old way of doing things, and that was the basics of how Spring did its magic using the @RunWith(SpringJUnit4ClassRunner.class) .

Now how can we do the same thing but on the method level? In JUnit 4, we couldn’t, but now, with the new release, it’s quite easy to add support for it.

JUnit5 comes with extensions, classes that extend JUnit5 to do more custom work. The Extention  interface is just a marker interface that all extension classes must implement.

We can’t do much if we rely on it by itself  the platform comes with a lot of interfaces and abstract classes that extend the Extension interface and that provide more methods that we can hook into and add our custom logic. To register an extension you just annotate your class with, @ExtendWith(MyExtension.class), register it programmatically via the @RegisterExtension annotated field, or using the ServiceLoader mechanism. In our case, the platform comes with an interface extending from the Extension interface called ParameterResolver, which defines methods to hook into the test execution and try and resolves test methods parameters at runtime.

The example here is going to use Java EE’s Context and Dependency Injection API and its implementation jboss.weld, but a more abstract way is shown in the repo, so make sure to check it out and the demos included for a better understanding of the project.

We will be using a simple Maven project structure, so we’ll start by adding a dependency on CDI in our pom.xml:

<dependency>
  <groupId>org.jboss.weld.se</groupId>
  <artifactId>weld-se-core</artifactId>
  <version>3.0.1.Final</version>
</dependency>

We will create a beans.xml file in our test/resources/META-INF directory (this is specific to CDI):

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
  version="1.1"bean-discovery-mode="all">
</beans>

Now we write our service class(es) …

public class DemoService {
  public String demo(String value) {
    return value + " is a demo";
  }
}

Now all that’s left is to create the extension and hook in our DI logic :

public class InjectionExtension implements ParameterResolver {

  private SeContainer container;

  /**
   * boot the CDI context
   */
  public InjectionExtension() {
    container = SeContainerInitializer.newInstance().initialize();
  }

  /**
   * determines weather we can inject all the parameters specified in the test method
   */
  @Override
  public boolean supportsParameter(ParameterContext parameterContext,
      ExtensionContext extensionContext) throws ParameterResolutionException {
    Method method = (Method) parameterContext.getDeclaringExecutable();
    Class<?>[] types = method.getParameterTypes();
    return Arrays.stream(types).allMatch(type -> container.select(type).isResolvable());
  }

  /**
   * resolve the return the object to be used in the test method
   */
  @Override
  public Object resolveParameter(ParameterContext parameterContext,
      ExtensionContext extensionContext) throws ParameterResolutionException {
    int paramIndex = parameterContext.getIndex();
    Method method = (Method) parameterContext.getDeclaringExecutable();
    Parameter param = method.getParameters()[paramIndex];
    return container.select(param.getType()).get();
  }
}

To use the extension, all you have to do is this:

/**
 * @author chermehdi
 */
@ExtendWith(InjectionExtension.class)
public class TestExtension {

  @Test
  void testExtension(DemoService service) {
    assertNotNull(service);
  }
}


Explanation

The supportsParameter method is called on each parameter found in your test methods, and if it returns true, then resolveParameter is called, if not the test crashes with an error message. Testing if we can provide the parameter or resolving the parameter is specific to each DI container; you just need to get a hold of the test method and you do the logic necessary to resolve the parameter . in this case we Create an SeContainer and try and resolve the parameter types, by selecting the type and using isResolvable method on the Instance returned.

Make sure you visit the repo of the project abstracting the idea — it’s called junit-di and the repo includes demos using CDI and a fixed dependency injection mechanism. Happy coding!

Testing Dependency injection JUnit

Published at DZone with permission of Mehdi Cheracher. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why Testing is a Long-Term Investment for Software Engineers
  • JUnit, 4, 5, Jupiter, Vintage
  • Readability in the Test: Exploring the JUnitParams
  • Creating Your Swiss Army Knife on Java Test Stack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!