Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JUnit 5: Injection Enabled Tests

DZone's Guide to

JUnit 5: Injection Enabled Tests

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

· Performance Zone ·
Free Resource

Built by operators for operators, the Sensu monitoring event pipeline empowers businesses to automate their monitoring workflows and gain deep visibility into their multi-cloud environments. Get started for free today.

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!

Download our guide to mitigating alert fatigue, with real-world tips on automating remediation and triage from an IT veteran.

Topics:
java ,unit testing ,junit 5 ,dependency injection ,junit ,tutorial ,performance

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}