0
0
JUnittesting~3 mins

Why @InjectMocks annotation in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to stop wasting time wiring up test objects and let your tests focus on what really matters!

The Scenario

Imagine you have a class that depends on several other classes to work properly. You want to test it, but you have to create and connect all those dependent objects by hand before each test.

The Problem

Manually creating and linking all dependencies is slow and boring. It's easy to make mistakes, like forgetting to set a dependency or linking the wrong one. This leads to tests that fail for the wrong reasons, wasting your time.

The Solution

The @InjectMocks annotation automatically creates the main object and injects all the mocked dependencies for you. This saves time, reduces errors, and keeps your tests clean and focused.

Before vs After
Before
MyService service = new MyService();
service.setRepo(mockRepo);
service.setHelper(mockHelper);
After
@InjectMocks
MyService service;
What It Enables

It enables fast, reliable setup of tested objects with all their dependencies mocked and ready, so you can focus on testing behavior, not setup.

Real Life Example

When testing a payment processor class that depends on a database and a notification service, @InjectMocks creates the processor and injects the mocked database and notification objects automatically.

Key Takeaways

Manual setup of dependencies is slow and error-prone.

@InjectMocks automates object creation and dependency injection.

This leads to cleaner, faster, and more reliable unit tests.