java怎么使用mock对象进行测试(Mockito) 使用Mockito创建与验证mock对象

答案:使用Mockito可创建mock对象并验证行为。首先添加依赖,通过@Mock或Mockito.mock()创建mock对象,用when().thenReturn()设定返回值,verify()验证方法调用次数及方式,结合JUnit注解初始化提升效率。

在Java单元测试中,使用Mockito框架可以轻松创建和验证mock对象,帮助我们隔离外部依赖,专注于被测代码逻辑。下面介绍如何用Mockito进行mock对象的创建与验证。

添加Mockito依赖

如果你使用Maven项目,在pom.xml中加入以下依赖:


    org.mockito
    m

ockito-core 5.7.0 test

Gradle用户则添加:

testImplementation 'org.mockito:mockito-core:5.7.0'

创建Mock对象

使用@Mock注解或Mockito.mock()方法都可以创建mock对象。

示例:模拟一个UserService接口

// 定义接口
public interface UserService {
    String getUserById(int id);
    boolean saveUser(User user);
}

// 测试类
public class UserControllerTest {

    @Mock
    private UserService userService;

    private UserController userController;

    @Before
    public void setUp() {
        MockitoAnnotations.openMocks(this);
        userController = new UserController(userService);
    }

    // 或者不用注解,直接手动创建
    // UserService userService = Mockito.mock(UserService.class);
}

设定Mock行为(Stu*g)

通过when(...).thenReturn(...)设定mock方法的返回值。

@Test
public void testGetUser_Success() {
    // 设定当调用getUserById(1)时,返回"John"
    when(userService.getUserById(1)).thenReturn("John");

    String result = userController.fetchUser(1);

    assertEquals("John", result);
}

也可以模拟异常情况:

when(userService.getUserById(999)).thenThrow(new RuntimeException("User not found"));

验证方法调用

使用verify()确认某个方法是否被调用,以及调用次数。

@Test
public void testSaveUser_CalledOnce() {
    User user = new User("Alice");

    userController.createUser(user);

    // 验证saveUser方法被调用了一次
    verify(userService, times(1)).saveUser(user);

    // 验证getUserById从未被调用
    verify(userService, never()).getUserById(anyInt());
}

常见验证方式:

  • times(n):调用n次
  • atLeastOnce():至少一次
  • never():从未调用
  • timeout(ms):在指定时间内被调用

基本上就这些。Mockito让测试更灵活,关键是理解mock对象不执行真实逻辑,而是由我们控制其行为,再验证交互是否符合预期。实际项目中结合JUnit和注解初始化会更简洁。不复杂但容易忽略细节,比如忘记openMocks或拼错方法名导致stub失效。