You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Mockito执行内部类RowMapper中mapRow方法的代码?

用Mockito测试RowMapper的mapRow方法逻辑

要执行并验证这段mapRow内部的业务代码,核心是用Mockito模拟它依赖的ResultSet对象,无需真实数据库就能完成逻辑校验。具体步骤如下:

步骤1:提取RowMapper为可引用对象

把原来的匿名内部类抽成单独的变量(或独立实现类),方便在测试中直接调用:

// 单独定义RowMapper实例
RowMapper<SomeObject> testRowMapper = new RowMapper<SomeObject>() {
    @Override
    public SomeObject mapRow(ResultSet r, int i) throws SQLException {
        // 保留你原有的业务逻辑代码
        String name = r.getString("user_name");
        int age = r.getInt("user_age");
        return new SomeObject(name, age);
    }
};

// 原有业务代码中使用该实例
simpleJDBCCall.returningResultSet("test", testRowMapper);

步骤2:编写Mockito测试用例

通过模拟ResultSet传入预设测试数据,直接调用mapRow方法验证逻辑:

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

@Test
public void testMapRowLogic() throws SQLException {
    // 1. 模拟ResultSet对象
    ResultSet mockResultSet = mock(ResultSet.class);

    // 2. 预设ResultSet的返回值,对应你mapRow里用到的字段
    when(mockResultSet.getString("user_name")).thenReturn("张三");
    when(mockResultSet.getInt("user_age")).thenReturn(25);

    // 3. 直接调用要测试的mapRow方法
    SomeObject result = testRowMapper.mapRow(mockResultSet, 0);

    // 4. 验证结果是否符合预期
    assertEquals("张三", result.getName());
    assertEquals(25, result.getAge());
}

关键点说明

  • 不需要mock RowMapper本身,我们要执行它的真实逻辑,Mockito仅用来模拟它依赖的ResultSet,避免依赖真实数据库连接和数据。
  • 如果你的mapRow包含异常处理逻辑,还可以用doThrow(SQLException.class).when(mockResultSet).getString(anyString())模拟SQL异常,验证异常处理逻辑是否正常。

内容的提问来源于stack exchange,提问作者H1312

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:25:01