Java Mock Mockito
π
2026-06-22 | π Java
Java Mock Testing Framework Mockito | Rookie Tutorial\n\n[ Java Common Libraries](#)\n\n* * *\n\n## What is Mock Testing?\n\nIn software development, unit testing is an important means of verifying code functionality. However, when our code depends on external systems (such as databases, network services, etc.), direct testing faces several issues:\n\n1. External dependencies may be unstable or unavailable\n2. Test execution speed becomes slow\n3. It's difficult to simulate various boundary conditions\n\nMock testing solves these problems by creating "stand-ins" for objects. Mock objects can:\n\n* Simulate the behavior of real objects\n* Verify whether interactions occur as expected\n* Not execute the actual logic of the real object\n\n* * *\n\n## Why Choose Mockito?\n\nMockito is currently the most popular Mock testing framework in the Java ecosystem, offering the following advantages:\n\n1. **Concise API**: Gentle learning curve, easy to get started\n2. **Powerful features**: Supports method call verification, return value setting, exception throwing, etc.\n3. **Good readability**: Test code is intuitive and easy to understand\n4. **Active community**: Continuously updated and maintained with good documentation\n\n* * *\n\n## Mockito Core Concepts\n\n### 1. Creating Mock Objects\n\n## Example\n\n// Method 1: Use static method\n\nList mockedList = Mockito.mock(List.class);\n\n// Method 2: Use annotations (requires MockitoJUnitRunner)\n\n @Mock\n\nList mockedList;\n\n### 2. Setting Method Behavior\n\n## Example\n\n// When calling mockedList.size() Return 100\n\n when(mockedList.size()).thenReturn(100);\n\n// When calling mockedList.get(0) Return 'first'\n\n when(mockedList.get(0)).thenReturn("first");\n\n// When calling mockedList.get(1) Throw exception\n\n when(mockedList.get(1)).thenThrow(new RuntimeException());\n\n### 3. Verifying Interactions\n\n## Example\n\n// Verify mockedList.add("one") Called once\n\n verify(mockedList).add("one");\n\n// Verify mockedList.clear() Never called\n\n verify(mockedList, never()).clear();\n\n// Verify mockedList.add("two") Called at least twice\n\n verify(mockedList, atLeast(2)).add("two");\n\n* * *\n\n## Mockito Practical Application Example\n\n### Testing User Service\n\nSuppose we have a `UserService` that depends on `UserRepository`:\n\n## Example\n\npublic class UserService {\n\nprivate UserRepository userRepository;\n\npublic UserService(UserRepository userRepository){\n\nthis.userRepository= userRepository;\n\n}\n\npublic User getUserById(Long id){\n\nreturn userRepository.findById(id)\n\n .orElseThrow(()->new UserNotFoundException("User not found"));\n\n}\n\n}\n\nUsing Mockito for testing:\n\n## Example\n\npublic class UserServiceTest {\n\n @Mock\n\nprivate UserRepository userRepository;\n\n@InjectMocks\n\nprivate UserService userService;\n\n@Before\n\npublic void setup(){\n\n MockitoAnnotations.initMocks(this);\n\n}\n\n@Test\n\npublic void testGetUserById_Success(){\n\n// Prepare test data\n\n User mockUser =new User(1L, "testUser");\n\n// Set Mock behavior\n\n when(userRepository.findById(1L))\n\n .thenReturn(Optional.of(mockUser));\n\n// Execute test\n\n User result = userService.getUserById(1L);\n\n// Verify result\n\n assertEquals("testUser", result.getUsername());\n\n verify(userRepository).findById(1L);\n\n}\n\n@Test(expected = UserNotFoundException.class)\n\npublic void testGetUserById_NotFound(){\n\n when(userRepository.findById(2L))\n\n .thenReturn(Optional.empty());\n\nuserService.getUserById(2L);\n\n}\n\n}\n\n* * *\n\n## Mockito Advanced Features\n\n### 1. Argument Matchers\n\n## Example\n\n// Any integer parameter\n\n when(mockedList.get(anyInt())).thenReturn("element");\n\n// Specific type parameter\n\n when(mockedList.contains(anyString())).thenReturn(true);\n\n// Custom matcher\n\n when(mockedList.add(argThat(arg -> arg.length()>5))).thenReturn(true);\n\n### 2. Verifying Call Order\n\n## Example\n\nInOrder inOrder = inOrder(mockedList);\n\ninOrder.verify(mockedList).add("first");\n\n inOrder.verify(mockedList).add("second");\n\n### 3. Partial Mock (Spy)\n\n## Example\n\nList realList =new ArrayList();\n\nList spyList = spy(realList);\n\n// Call real method\n\n spyList.add("real");\n\n// Mock specific method\n\n doReturn(100).when(spyList).size();\n\n* * *\n\n## Best Practices\n\n1. **Don't overuse Mock**: Only mock necessary dependencies to maintain test authenticity\n2. **Verify interactions moderately**: Focus on important interactions, don't verify every method call\n3. **Keep tests concise**: Each test method should test only one functional point\n4. **Organize test code properly**: Use @Before for common setup\n5. **Combine with other testing tools**: Use in conjunction with JUnit, AssertJ, etc.\n\n* * *\n\n## Frequently Asked Questions\n\n### Q: What's the difference between Mockito and PowerMock?\n\nA: Mockito is mainly used for mocking ordinary objects, while PowerMock can mock static methods, constructors, etc. However, PowerMock breaks test isolation, so it's recommended to prioritize using Mockito.\n\n### Q: When should I use Spy instead of Mock?\n\nA: Use Spy when you need most of the real behavior and only want to modify a few methods. Use Mock when you need complete control over the object's behavior.\n\n### Q: Can Mockito be used for final classes or methods?\n\nA: Starting from Mockito 2.1.0, final classes and methods can be mocked through configuration, but the `mockito-inline` dependency needs to be added.\n\n* * *\n\n## Related Links\n\n1. (https://site.mockito.org/)\n2. (https://github.com/mockito/mockito)\n\n[ Java Common Libraries](#)