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

JUnit Mock时getSession()触发空指针异常,求解决方案

解决getSession()空指针的JUnit Mock方案

问题根源

你遇到的空指针源于两个核心问题:

  1. getSession()方法未被正确Mock,调用真实方法返回了null
  2. 即便Mock了Session,createNativeQuery()返回的Query对象也是null,后续调用executeUpdate()同样会触发空指针

修正后的完整JUnit代码

@ExtendWith(MockitoExtension.class)
public class TmsCfsCashflowsDaoImplTest { // 替换为你的实际DAO测试类名
    @Mock
    private Session hibernateSession;
    @Mock
    private Query mockQuery;
    @InjectMocks
    private TmsCfsCashflowsDaoImpl daoImpl; // 你的DAO实现类实例

    @BeforeEach
    public void setUp() {
        // Mock DAO实例的getSession()方法,返回预设的mock Session
        when(daoImpl.getSession()).thenReturn(hibernateSession);
        // Mock Session的createNativeQuery方法,返回mock的Query对象
        when(hibernateSession.createNativeQuery(anyString())).thenReturn(mockQuery);
        // Mock Query的executeUpdate方法,返回预期的更新行数
        when(mockQuery.executeUpdate()).thenReturn(1);
    }

    @Test
    public void updateDataTest() {
        // 准备测试数据
        List<Integer> cashIdList = new ArrayList<>();
        cashIdList.add(10);

        // 执行目标方法
        daoImpl.updateData(cashIdList);

        // 验证核心调用逻辑
        verify(daoImpl, times(1)).getSession();
        // 验证生成的SQL是否符合预期(可根据Constants.UPDATE_QUERY的实际值调整expectedQuery)
        String expectedQuery = Constants.UPDATE_QUERY + "(10)";
        verify(hibernateSession, times(1)).createNativeQuery(eq(expectedQuery));
        // 验证更新操作被执行
        verify(mockQuery, times(1)).executeUpdate();
    }
}

关键修正点说明

  • 正确Mock getSession():必须明确指定Mock的是daoImpl实例的getSession()方法(而非直接调用getSession()),确保返回预设的mock Session对象
  • Mock Query对象:Session的createNativeQuery()必须返回一个mock的Query实例,否则调用executeUpdate()会触发空指针
  • 验证逻辑调整:原测试中验证updateData()被调用没有实际意义,应验证底层的Session、Query方法是否按预期执行,确保业务逻辑正确

额外注意事项

  • 若使用JUnit 4,将@ExtendWith(MockitoExtension.class)替换为@RunWith(MockitoJUnitRunner.class)
  • 确保导入正确的Mockito依赖包(org.mockito.junit.jupiter.MockitoExtension、org.mockito.Mock等)
  • 若getSession()是从父类继承的方法,或Session由Spring注入,需确保@InjectMocks能正确将mock Session注入到DAO实例中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:37:34