Bird
Raised Fist0
JUnittesting~8 mins

@InjectMocks annotation in JUnit - Framework Patterns

Choose your learning style10 modes available
Framework Mode - @InjectMocks annotation
Folder Structure for JUnit with Mockito (@InjectMocks)
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           ├── service/
│   │           │   └── UserService.java
│   │           └── repository/
│   │               └── UserRepository.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── service/
│               │   └── UserServiceTest.java  <--- Test class with @InjectMocks
│               └── repository/
│                   └── UserRepositoryTest.java
├── build.gradle or pom.xml
└── src/test/resources/
    └── test.properties
Test Framework Layers
  • Test Classes: Classes like UserServiceTest where @InjectMocks is used to create the class under test with its dependencies injected.
  • Mock Objects: Dependencies annotated with @Mock that are injected into the class under test.
  • Service Layer: Actual business logic classes (e.g., UserService).
  • Repository Layer: Data access classes (e.g., UserRepository), often mocked in tests.
  • Utilities: Helper classes for common test setup or data creation.
  • Configuration: Setup for Mockito and JUnit integration, e.g., @ExtendWith(MockitoExtension.class).
Configuration Patterns
  • Use @ExtendWith(MockitoExtension.class) on test classes to enable Mockito annotations.
  • Annotate dependencies with @Mock to create mock instances.
  • Annotate the class under test with @InjectMocks to inject mocks automatically.
  • Use src/test/resources/test.properties or similar for environment-specific test data.
  • Configure build tool (Maven/Gradle) to include Mockito and JUnit Jupiter dependencies.
Test Reporting and CI/CD Integration
  • JUnit generates XML test reports by default, which CI tools (Jenkins, GitHub Actions) can consume.
  • Use build tools to run tests and generate reports automatically on each commit.
  • Mockito tests with @InjectMocks appear as normal JUnit tests in reports.
  • Integrate code coverage tools (JaCoCo) to measure test coverage.
  • Fail builds if tests with mocks fail, ensuring dependency injection correctness.
Best Practices for Using @InjectMocks
  1. Keep Tests Focused: Use @InjectMocks to test one class at a time with its dependencies mocked.
  2. Use Constructor Injection: Prefer constructor injection in your classes to make @InjectMocks work reliably.
  3. Initialize Mocks Properly: Use @ExtendWith(MockitoExtension.class) or MockitoAnnotations.openMocks(this) to initialize mocks.
  4. Avoid Mixing Real and Mocked Dependencies: Keep dependencies either fully mocked or real to avoid confusion.
  5. Write Clear Assertions: Assert behavior on the class under test, not on mocks directly.
Self Check

Where in this folder structure would you add a new test class for a service named OrderService that uses @InjectMocks?

Key Result
Use @InjectMocks in JUnit tests to automatically inject mock dependencies into the class under test for clean, isolated unit testing.

Practice

(1/5)
1. What is the primary purpose of the @InjectMocks annotation in JUnit testing?
easy
A. To spy on real objects without mocking
B. To create the class under test and inject mock dependencies automatically
C. To create mock objects without injecting them
D. To run tests in parallel threads

Solution

  1. Step 1: Understand the role of @InjectMocks

    @InjectMocks creates an instance of the class under test and injects mocks into it automatically.
  2. Step 2: Compare with other annotations

    @Mock creates mock objects, but does not inject them. @Spy wraps real objects. @InjectMocks handles injection.
  3. Final Answer:

    To create the class under test and inject mock dependencies automatically -> Option B
  4. Quick Check:

    @InjectMocks = auto-inject mocks [OK]
Hint: Remember: @InjectMocks builds and injects mocks automatically [OK]
Common Mistakes:
  • Confusing @InjectMocks with @Mock
  • Thinking @InjectMocks creates mocks instead of injecting
  • Assuming @InjectMocks runs tests or manages threads
2. Which of the following is the correct way to declare a field with @InjectMocks in a JUnit 5 test class?
easy
A. @InjectMocks private Service service;
B. @InjectMocks Service service = new Service();
C. @InjectMocks private Service service = new Service();
D. @InjectMocks Service service;

Solution

  1. Step 1: Check field declaration syntax

    Fields with @InjectMocks should be private and declared without manual instantiation.
  2. Step 2: Identify correct syntax

    @InjectMocks private Service service; declares a private field with @InjectMocks without manual instantiation, letting the framework create it.
  3. Final Answer:

    @InjectMocks private Service service; -> Option A
  4. Quick Check:

    Private field + no manual new = correct [OK]
Hint: Use private fields without 'new' for @InjectMocks [OK]
Common Mistakes:
  • Manually instantiating the field defeats @InjectMocks purpose
  • Using package-private or public fields without private
  • Missing semicolon or incorrect syntax
3. Given the following test code snippet, what will be the output of service.process() if dependency.doWork() is mocked to return "mocked"?
class Dependency {
    String doWork() { return "real"; }
}

class Service {
    Dependency dependency;
    String process() { return dependency.doWork(); }
}

@InjectMocks
Service service;

@Mock
Dependency dependency;

@BeforeEach
void setup() {
    MockitoAnnotations.openMocks(this);
    when(dependency.doWork()).thenReturn("mocked");
}

@Test
void testProcess() {
    System.out.println(service.process());
}
medium
A. Compilation error
B. "real"
C. NullPointerException
D. "mocked"

Solution

  1. Step 1: Understand @InjectMocks and @Mock interaction

    @InjectMocks creates Service and injects the mocked Dependency instance into it.
  2. Step 2: Analyze method call and mock behavior

    dependency.doWork() is mocked to return "mocked", so service.process() returns "mocked".
  3. Final Answer:

    "mocked" -> Option D
  4. Quick Check:

    Mocked method returns "mocked" [OK]
Hint: Mocks override real methods; expect mocked return values [OK]
Common Mistakes:
  • Expecting real method output instead of mocked
  • Forgetting to initialize mocks with openMocks
  • Assuming dependency is null causing NullPointerException
4. Consider the following test setup:
@InjectMocks
Service service;

@Mock
Dependency dependency;

@BeforeEach
void setup() {
    MockitoAnnotations.openMocks(this);
}

@Test
void test() {
    System.out.println(service.process());
}

When running the test, a NullPointerException occurs at service.process(). What is the most likely cause?
medium
A. The @InjectMocks annotation is applied to the wrong class
B. The @Mock annotation is missing
C. The dependency field in Service is not initialized or injected
D. MockitoAnnotations.openMocks(this) was not called

Solution

  1. Step 1: Identify cause of NullPointerException

    NullPointerException at service.process() means dependency inside Service is null.
  2. Step 2: Check injection of mocks

    @InjectMocks should inject mocks into Service fields, but if Service's dependency field is not properly declared or missing setter, injection fails.
  3. Final Answer:

    The dependency field in Service is not initialized or injected -> Option C
  4. Quick Check:

    NullPointerException = missing injection [OK]
Hint: NullPointerException often means mock not injected properly [OK]
Common Mistakes:
  • Assuming missing @Mock causes NPE (it causes different errors)
  • Thinking openMocks call is missing when it is present
  • Confusing @InjectMocks placement with injection failure
5. You have a class OrderService that depends on PaymentService and InventoryService. You want to write a JUnit test using @InjectMocks to inject mocks of both dependencies. Which setup correctly uses @InjectMocks and @Mock to achieve this?
hard
A. @InjectMocks OrderService orderService; @Mock PaymentService paymentService; @Mock InventoryService inventoryService;
B. @Mock OrderService orderService; @InjectMocks PaymentService paymentService; @InjectMocks InventoryService inventoryService;
C. @InjectMocks OrderService orderService = new OrderService(); @Mock PaymentService paymentService; @Mock InventoryService inventoryService;
D. @Mock OrderService orderService; @Mock PaymentService paymentService; @Mock InventoryService inventoryService;

Solution

  1. Step 1: Identify the class under test

    OrderService is the class under test, so it should be annotated with @InjectMocks.
  2. Step 2: Identify dependencies to mock

    PaymentService and InventoryService are dependencies, so they should be annotated with @Mock.
  3. Step 3: Check for manual instantiation

    OrderService should not be manually instantiated when using @InjectMocks to allow automatic injection.
  4. Final Answer:

    @InjectMocks OrderService orderService; @Mock PaymentService paymentService; @Mock InventoryService inventoryService; -> Option A
  5. Quick Check:

    Class under test @InjectMocks + dependencies @Mock [OK]
Hint: InjectMocks on class under test; Mocks on dependencies [OK]
Common Mistakes:
  • Annotating dependencies with @InjectMocks instead of @Mock
  • Manually instantiating class under test with @InjectMocks
  • Annotating class under test with @Mock instead of @InjectMocks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard