Bird
Raised Fist0
JUnittesting~15 mins

@Mock annotation in JUnit - Build an Automation Script

Choose your learning style10 modes available
Verify behavior of a service method using @Mock annotation
Preconditions (2)
Step 1: Create a test class for the service
Step 2: Annotate the repository interface field with @Mock
Step 3: Annotate the service class field with @InjectMocks
Step 4: Initialize mocks using MockitoAnnotations.openMocks(this) in a setup method
Step 5: Stub the repository method to return a fixed value when called
Step 6: Call the service method that uses the repository
Step 7: Verify the returned value matches the stubbed value
✅ Expected Result: The service method returns the stubbed value from the mocked repository, confirming @Mock works correctly
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Assert that the service method returns the expected stubbed value
Verify that the repository method was called exactly once
Best Practices:
Use @Mock to create mock objects
Use @InjectMocks to inject mocks into the class under test
Initialize mocks in a @BeforeEach setup method
Use Mockito's when-thenReturn for stubbing
Use verify to check interactions with mocks
Automated Solution
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

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

    @Test
    void testGetUserNameReturnsStubbedValue() {
        // Arrange
        when(userRepository.findUserNameById(1)).thenReturn("Alice");

        // Act
        String result = userService.getUserName(1);

        // Assert
        assertEquals("Alice", result, "The service should return the stubbed user name");
        verify(userRepository, times(1)).findUserNameById(1);
    }
}

// Supporting classes
interface UserRepository {
    String findUserNameById(int id);
}

class UserService {
    private final UserRepository userRepository;

    UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    String getUserName(int id) {
        return userRepository.findUserNameById(id);
    }
}

This test class demonstrates how to use the @Mock annotation to create a mock of UserRepository. The @InjectMocks annotation injects this mock into the UserService instance.

In the setUp method, MockitoAnnotations.openMocks(this) initializes the mocks before each test.

The test method testGetUserNameReturnsStubbedValue stubs the repository method findUserNameById to return "Alice" when called with 1.

Then it calls the service method and asserts the returned value matches the stubbed value. It also verifies the repository method was called exactly once.

This setup ensures the service behavior is tested in isolation from the real repository, using the mock created by @Mock.

Common Mistakes - 4 Pitfalls
Not initializing mocks with MockitoAnnotations.openMocks(this)
Using @Mock but not using @InjectMocks for the class under test
Stubbing methods after calling the service method
Using real implementations instead of mocks for dependencies
Bonus Challenge

Now add data-driven testing with 3 different user IDs and expected names

Show Hint

Practice

(1/5)
1. What is the main purpose of the @Mock annotation in JUnit testing?
easy
A. To create fake objects that simulate real dependencies for testing
B. To run tests in parallel threads
C. To generate test reports automatically
D. To connect to a real database during tests

Solution

  1. Step 1: Understand the role of @Mock

    The @Mock annotation is used to create fake objects that imitate real dependencies in tests.
  2. Step 2: Identify the purpose in testing context

    This helps isolate the code being tested from external systems or complex objects.
  3. Final Answer:

    To create fake objects that simulate real dependencies for testing -> Option A
  4. Quick Check:

    @Mock creates fake objects [OK]
Hint: Mocks create fake objects to isolate tests [OK]
Common Mistakes:
  • Thinking @Mock runs tests in parallel
  • Confusing @Mock with test report generation
  • Assuming @Mock connects to real databases
2. Which of the following is the correct way to declare a mock object using @Mock in a JUnit 5 test class?
easy
A. @Mock private MyService service;
B. @Mock MyService service = new MyService();
C. @Mock public void service();
D. @Mock MyService service = null;

Solution

  1. Step 1: Check correct syntax for @Mock field declaration

    The mock object should be declared as a private field with the @Mock annotation and no initialization.
  2. Step 2: Identify the correct option

    @Mock private MyService service; correctly declares: @Mock private MyService service; without initializing it.
  3. Final Answer:

    @Mock private MyService service; -> Option A
  4. Quick Check:

    Declare mock as private field without initialization [OK]
Hint: Declare mocks as private fields without new keyword [OK]
Common Mistakes:
  • Initializing mock objects manually
  • Using @Mock on methods instead of fields
  • Declaring mocks as public or with invalid syntax
3. Given the following JUnit 5 test code snippet, what will be the output of service.getData() when called inside the test?
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

class MyServiceTest {
  @Mock
  MyService service;

  @Test
  void testGetData() {
    MockitoAnnotations.openMocks(this);
    when(service.getData()).thenReturn("mocked data");
    System.out.println(service.getData());
  }
}
medium
A. Original data from MyService
B. null
C. Throws NullPointerException
D. mocked data

Solution

  1. Step 1: Understand mock initialization

    The call to MockitoAnnotations.openMocks(this) initializes the @Mock annotated fields.
  2. Step 2: Analyze the stubbed method behavior

    The line when(service.getData()).thenReturn("mocked data") sets the mock to return "mocked data" when getData() is called.
  3. Final Answer:

    mocked data -> Option D
  4. Quick Check:

    Stubbed mock method returns set value [OK]
Hint: Initialize mocks and stub methods to control output [OK]
Common Mistakes:
  • Forgetting to initialize mocks before use
  • Expecting real method output instead of stubbed
  • Confusing null return with stubbed return
4. Identify the error in the following JUnit 5 test code using @Mock:
import org.junit.jupiter.api.Test;
import org.mockito.Mock;

class UserServiceTest {
  @Mock
  UserRepository repo;

  @Test
  void testFindUser() {
    when(repo.findUserById(1)).thenReturn(new User(1, "Alice"));
    UserService service = new UserService(repo);
    User user = service.findUser(1);
    assertEquals("Alice", user.getName());
  }
}
medium
A. The test method is missing the @Mock annotation
B. The when method is used incorrectly
C. Mocks are not initialized before use
D. UserService constructor cannot accept mocks

Solution

  1. Step 1: Check mock initialization

    The code declares @Mock UserRepository repo; but never initializes mocks with MockitoAnnotations.openMocks(this) or similar.
  2. Step 2: Understand consequence of missing initialization

    Without initialization, repo is null, so calling when(repo.findUserById(1)) causes a NullPointerException.
  3. Final Answer:

    Mocks are not initialized before use -> Option C
  4. Quick Check:

    Always initialize mocks before using them [OK]
Hint: Always initialize mocks before calling methods on them [OK]
Common Mistakes:
  • Forgetting MockitoAnnotations.openMocks(this)
  • Assuming @Mock auto-initializes mocks
  • Misusing when() without initialized mocks
5. You want to test a service method that depends on two different collaborators. You use @Mock to create fake objects for both. Which of the following is the best practice to ensure your mocks work correctly in the test?
hard
A. Declare mocks as local variables inside test methods
B. Initialize mocks with MockitoAnnotations.openMocks(this) in a setup method
C. Use real instances instead of mocks for better accuracy
D. Manually instantiate mocks with new keyword

Solution

  1. Step 1: Understand mock initialization best practice

    Mocks annotated with @Mock must be initialized before use, typically by calling MockitoAnnotations.openMocks(this) in a setup method.
  2. Step 2: Evaluate other options

    Manually creating mocks with new is incorrect; real instances break isolation; local variables lose scope and initialization benefits.
  3. Final Answer:

    Initialize mocks with MockitoAnnotations.openMocks(this) in a setup method -> Option B
  4. Quick Check:

    Initialize mocks in setup for reliable tests [OK]
Hint: Initialize all @Mock fields in setup method [OK]
Common Mistakes:
  • Creating mocks manually with new keyword
  • Using real objects instead of mocks
  • Declaring mocks inside test methods without initialization
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