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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Understanding the Dependency Injection Lifecycle: Singleton, Scoped, and Transient With Detailed Examples
  • Best Practices for Writing Unit Tests: A Comprehensive Guide
  • Building Web Applications With .NET: Best Practices and Techniques

Trending

  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • Scaling Microservices With Docker and Kubernetes on Production
  • Rust, WASM, and Edge: Next-Level Performance
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Field Injection When Mocking Frameworks Fail

Field Injection When Mocking Frameworks Fail

Learn more about field injection with mocking frameworks, and CDI in applications when unit testing Java classes.

By 
Ivo Woltring user avatar
Ivo Woltring
·
Mar. 14, 16 · Analysis
Likes (11)
Comment
Save
Tweet
Share
22.9K Views

Join the DZone community and get the full member experience.

Join For Free

Challenge

You are using Dependency Injection (CDI) in your application and you want to unit test your Java classes without making it an integration test by using Weld or Arquillian. You are using a Mocking framework like Mockito or EasyMock but still have trouble getting all your dependencies injected into the class because one of the injections is a String type or another final class.

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.lang.String
Mockito cannot mock/spy following:
   - final classes
   - anonymous classes
   - primitive types

I personally came by this challenge after writing a couple of @Producer methods for injecting a property from a property file. So in effect I was injecting a String and I had trouble writing a test for it.

Solution

Create your own small injection utility method:

  public static void injectField(final Object injectable, 
                                 final String fieldname, 
                                 final Object value) {
      try {
          final java.lang.reflect.Field field = injectable.getClass()
                                                          .getDeclaredField(fieldname);
          final boolean origionalValue = field.isAccessible();
          field.setAccessible(true);
          field.set(injectable, value);
          field.setAccessible(origionalValue);
      } catch (final NoSuchFieldException | IllegalAccessException e) {
          throw new RuntimeException(e.getMessage(), e);
      }
  }

So if you have a class like this, with an @Inject and no setter, you want to test:

package nl.ivonet.example;
import javax.inject.Inject;
public class Greeting {
    @Inject
    private String greeting;

    @Override
    public String toString() {
        return this.greeting;
    }
}

You can test it like this:

package nl.ivonet.example;
import org.junit.Test;
import static nl.ivonet.example.utility.CDI.injectField;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class GreetingTest {
    @Test
    public void testToString() throws Exception {
        Greeting greeting = new Greeting();
        injectField(greeting, "greeting", "Hello, world");
        assertThat(greeting.toString(), is("Hello, world"));
    }
}

For other Injectables, you can still use Mockito or your Mocking framework of choice but for final classes you can do the above.

Have fun,

Ivo.

Dependency injection Framework unit test

Published at DZone with permission of Ivo Woltring. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Understanding the Dependency Injection Lifecycle: Singleton, Scoped, and Transient With Detailed Examples
  • Best Practices for Writing Unit Tests: A Comprehensive Guide
  • Building Web Applications With .NET: Best Practices and Techniques

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!