Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Mock Testing Framework Mockito

Java Mock Testing Framework Mockito

Common Java Libraries Common Java Libraries


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:

  1. External dependencies may be unstable or unavailable
  2. Test execution becomes slower
  3. Difficult to simulate various boundary conditions

Mock testing (simulation testing) solves these problems by creating "stand-ins" for objects. Mock objects can:


Why choose Mockito?

Mockito is currently the most popular Mock testing framework in the Java ecosystem, and it has the following advantages:

  1. Concise API: Gentle learning curve, easy to get started
  2. Powerful features: Supports method call verification, return value setting, exception throwing, etc.
  3. Good readability: Test code is intuitive and easy to understand
  4. 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

  1. Do not overuse Mock: Only mock necessary dependencies to keep tests realistic
  2. Verify interactions in moderation: Focus on important interactions; do not verify every method call
  3. Keep tests concise: Each test method should test only one feature point
  4. Organize test code reasonably: Use @Before for common setup
  5. 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.


Related links

  1. Mockito official documentation
  2. Mockito GitHub repository

Common Java Libraries Common Java Libraries