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
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

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

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

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

  • Demystifying Static Mocking With Mockito
  • Creating Your Swiss Army Knife on Java Test Stack
  • IntelliJ Integration for Mockito
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Scalable System Design: Core Concepts for Building Reliable Software
  • Google Cloud Document AI Basics
  1. DZone
  2. Coding
  3. Java
  4. When Mockito’s InjectMocks Does Not Inject Mocks

When Mockito’s InjectMocks Does Not Inject Mocks

How to perform unit tests in Java using Mockito's InjectMocks tool and how to get it working.

By 
Dror Helper user avatar
Dror Helper
·
Dec. 03, 15 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
89.9K Views

Join the DZone community and get the full member experience.

Join For Free

Looking back at the time wasted yesterday while trying to make a trivial functionality work makes me wonder if it was a good idea to begin with…

It all started  (and ended) yesterday while I was mentoring a team on the fine art of Java unit testing.

We’ve decided to use Mockito’s InjectMocks due to the fact that most of the project's classes used Spring to fill private fields (don’t get me started).

For those of you who never used InjectMocks before — in the Mockito world we can auto-magically initialize and inject mock objects into the class under test. And it’s all done using annotations.

And so if I have the following class:

public class MyClass {

    @Resource
    private INetworkService networkService;

    @Resource
    private IFileService fileService;

    public boolean SomeMethod(){
        // some logic here

        // More logic here
        networkService.Send();

        return true;
    }
}

I can write a test fixture that looks like this:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
    @Mock
    private INetworkService networkService;

    @Mock
    private IFileService fileService;

    @InjectMocks
    MyClass myClass;

    @Test
    public void testSomeMethod() {
        boolean result = myClass.SomeMethod();

        assertTrue(result);
    }
}

And so the two dependencies (marked with @Mock) would be faked and inserted into MyClass by constructor, property or field injection.

The problem was that we couldn’t get it to work. The mocks were initialized and the class was created - without the dependencies. It took us some time but finally we’ve found the reason: the real class looked something like this — can you spot the difference?

public class MyClass {

    @Resource
    private INetworkService networkService;

    @Resource
    private IFileService fileService;

    private Integer version;

    public MyClass(Integer version) {
        this.version = version;
    }

    public boolean SomeMethod(){
        // some logic here

        // More logic here
        networkService.Send();

        return true;
    }
}

Did you see it?

In our real class we had a non-empty constructor which InjectMocks tried to use, but passed null since Integer canno be mocked by Mockito (it’s a final class). OnceMockito found a constructor to try and to use it didn’t even try to inject the two fields (lazy bastard). And so the dependencies inside the MyClass remained null causing a null reference exception to be thrown once used.

It’s not that Mockito guys didn’t do a good job, this behavior is documented – which makes it yet another case of RTFM.

The problem is that the tests who successfully run using this mechanism could one day fail just because someone decided to add another constructor.

Happy coding!

Mockito

Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Demystifying Static Mocking With Mockito
  • Creating Your Swiss Army Knife on Java Test Stack
  • IntelliJ Integration for Mockito
  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services

Partner Resources

×

Comments

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: