Java Mock Testing Framework Mockito
What is Mock testing?
In 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.), testing directly faces several problems:
- External dependencies may be unstable or unavailable
- Test execution becomes slower
- Difficult to simulate various boundary conditions
Mock testing (simulation testing) solves these problems by creating "stand-ins" for objects. Mock objects can:
- Simulate the behavior of real objects
- Verify that interactions occur as expected
- Not execute the actual logic of real objects
Why choose Mockito?
Mockito is currently the most popular Mock testing framework in the Java ecosystem, and it has the following advantages:
- Concise API: Gentle learning curve, easy to get started
- Powerful features: Supports method call verification, return value setting, exception throwing, etc.
- Good readability: Test code is intuitive and easy to understand
- Active community: Continuous updates and maintenance, with comprehensive documentation
Mockito core concepts
1. Creating Mock objects
Example
// Method 1: Using the static method
List
mockedList
=
Mockito.
mock
(
List
.
class
)
;
// Method 2: Using annotations (requires MockitoJUnitRunner)
@Mock
List
mockedList
;
2. Setting method behavior
Example
// Return 100 when mockedList.size() is called
when
(
mockedList.
size
(
)
)
.
thenReturn
(
100
)
;
// Return "first" when mockedList.get(0) is called
when
(
mockedList.
get
(
0
)
)
.
thenReturn
(
"first"
)
;
// Throw an exception when mockedList.get(1) is called
when
(
mockedList.
get
(
1
)
)
.
thenThrow
(
new
RuntimeException
(
)
)
;
3. Verifying interactions
Example
// Verify that mockedList.add("one") was called once
verify
(
mockedList
)
.
add
(
"one"
)
;
// Verify that mockedList.clear() was never called
verify
(
mockedList, never
(
)
)
.
clear
(
)
;
// Verify that mockedList.add("two") was called at least twice
verify
(
mockedList, atLeast
(
2
)
)
.
add
(
"two"
)
;
Mockito practical application example
Testing the user service
Suppose we have a UserService that depends on UserRepository:
Example
public
class
UserService
{
private
UserRepository userRepository
;
public
UserService
(
UserRepository userRepository
)
{
this
.
userRepository
=
userRepository
;
}
public
User getUserById
(
Long
id
)
{
return
userRepository.
findById
(
id
)
.
orElseThrow
(
(
)
->
new
UserNotFoundException
(
"User not found"
)
)
;
}
}
Test using Mockito:
Example
public
class
UserServiceTest
{
@Mock
private
UserRepository userRepository
;
@InjectMocks
private
UserService userService
;
@Before
public
void
setup
(
)
{
MockitoAnnotations.
initMocks
(
this
)
;
}
@Test
public
void
testGetUserById_Success
(
)
{
// Prepare test data
User mockUser
=
new
User
(
1L,
"testUser"
)
;
// Set up Mock behavior
when
(
userRepository.
findById
(
1L
)
)
.
thenReturn
(
Optional.
of
(
mockUser
)
)
;
// Execute the test
User result
=
userService.
getUserById
(
1L
)
;
// Verify the result
assertEquals
(
"testUser"
, result.
getUsername
(
)
)
;
verify
(
userRepository
)
.
findById
(
1L
)
;
}
@Test
(
expected
=
UserNotFoundException.
class
)
public
void
testGetUserById_NotFound
(
)
{
when
(
userRepository.
findById
(
2L
)
)
.
thenReturn
(
Optional.
empty
(
)
)
;
userService.
getUserById
(
2L
)
;
}
}
Mockito advanced features
1. Argument matchers
Example
// Any integer argument
when
(
mockedList.
get
(
anyInt
(
)
)
)
.
thenReturn
(
"element"
)
;
// Arguments of a specific type
when
(
mockedList.
contains
(
anyString
(
)
)
)
.
thenReturn
(
true
)
;
// Custom matcher
when
(
mockedList.
add
(
argThat
(
arg
->
arg.
length
(
)
5
)
)
)
.
thenReturn
(
true
)
;
2. Verifying call order
Example
InOrder inOrder
=
inOrder
(
mockedList
)
;
inOrder.
verify
(
mockedList
)
.
add
(
"first"
)
;
inOrder.
verify
(
mockedList
)
.
add
(
"second"
)
;
3. Partial Mock (Spy)
Example
List
realList
=
new
ArrayList
(
)
;
List
spyList
=
spy
(
realList
)
;
// Call the real method
spyList.
add
(
"real"
)
;
// Mock a specific method
doReturn
(
100
)
.
when
(
spyList
)
.
size
(
)
;
Best Practices
- Do not overuse Mock: Only mock necessary dependencies to keep tests realistic
- Verify interactions in moderation: Focus on important interactions; do not verify every method call
- Keep tests concise: Each test method should test only one feature point
- Organize test code reasonably: Use @Before for common setup
- Combine with other testing tools: Use together with JUnit, AssertJ, etc.
Frequently Asked Questions
Q: What is the difference between Mockito and PowerMock?
A: Mockito is mainly used for mocking ordinary objects, while PowerMock can mock static methods, constructors, etc. However, PowerMock breaks test isolation, so it is recommended to prefer Mockito.
Q: When should you use Spy instead of Mock?
A: Use Spy when you need most of the real behavior and only modify a few methods. Use Mock when you need full control over the object's behavior.
Q: Can Mockito be used for final classes or methods?
A: Starting from Mockito 2.1.0, final classes and methods can be mocked through configuration, but you need to add mockito-inline dependency.
Common Java Libraries