
在进行单元测试时,我们经常需要模拟那些依赖于外部资源或复杂协作的类。一个常见模式是使用一个静态字段(如HibernateSessionManager.current)来提供服务实例,并通过其方法(如withSession)执行业务逻辑。当withSession方法内部包含一个Lambda表达式,并且该Lambda表达式又调用了其他模拟对象的方法时,测试覆盖率可能会出现问题。
考虑以下getMBCSessionByGuid方法,它通过HibernateSessionManager.current.withSession来获取一个Mbc_session对象:
public Mbc_session getMBCSessionByGuid(String sessionGuid) { 
  try { 
    return HibernateSessionManager.current.withSession(hibernateSession -> { 
       return hibernateSession.get(Mbc_session.class, sessionGuid); 
   }); 
} 
catch (Exception e) { 
  // 错误处理逻辑
  logger.error().logFormattedMessage(Constants.MBC_SESSION_GET_ERROR_STRING, 
    e.getMessage()); 
  throw new DAOException(ErrorCode.MBC_1510.getCode(), ErrorCode.MBC_1510.getErrorMessage() + ",Operation: getMBCSessionByGuid"); 
 } 
}在测试中,我们通常会像这样初始化模拟对象:
public static void initMocks(Session session) { 
  // 模拟HibernateSessionManager.current实例
  HibernateSessionManager.current = mock(HibernateSessionManager.class, Mockito.RETURNS_DEEP_STUBS); 
  // 模拟HibernateTransactionManager.current实例
  HibernateTransactionManager.current = mock(HibernateTransactionManager.class, Mockito.RETURNS_DEEP_STUBS); 
  // 尝试对withSession方法调用真实方法
  // doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Consumer.class)); 
  // 模拟getSession方法
  when(HibernateSessionManager.current.getSession()).thenReturn(session); 
}以及一个典型的测试用例:
@Test 
public void test_getMBCSessionByGuid() { 
  Mbc_session mbcSession = new Mbc_session(); 
  String sessionGuid = "session GUID"; 
  // 确保getSession返回模拟的session
  when(HibernateSessionManager.current.getSession()).thenReturn(session); 
  // 模拟session.get方法的行为
  when(session.get(Mbc_session.class, sessionGuid)).thenReturn(mbcSession); 
  Mbc_session mbcSession2 = mbc_sessionDao.getMBCSessionByGuid(sessionGuid); 
  // 断言
  assertNull(mbcSession2); // 假设期望为null,或根据业务逻辑断言
} 尽管上述测试通过,但代码覆盖率报告显示,return hibernateSession.get(Mbc_session.class, sessionGuid); 这一行代码并未被执行到。这表明我们的模拟配置未能正确触发withSession内部的Lambda逻辑。
问题的核心在于withSession方法存在重载,并且测试代码在模拟时错误地选择了其中一个。让我们来看一下HibernateSessionManager中可能存在的withSession方法签名:
// 签名1:接受一个Consumer<Session>,不返回任何值
public void withSession(Consumer<Session> task) { 
    Session hibernateSession = getSession(); 
    try { 
       task.accept(hibernateSession); // 执行任务,不关心返回值
    } finally { 
       HibernateSessionManager.current.closeSession(hibernateSession); 
    } 
} 
// 签名2:接受一个Function<Session, Mbc_session>,返回一个Mbc_session
// (或其他泛型类型,取决于Function的第二个类型参数)
public Mbc_session withSession(Function<Session, Mbc_session> task) {
    Session hibernateSession = getSession();
    try {
        return task.apply(hibernateSession); // 执行任务并返回结果
    } finally {
        HibernateSessionManager.current.closeSession(hibernateSession);
    }
}观察getMBCSessionByGuid方法中传递给withSession的Lambda表达式:
hibernateSession -> { 
   return hibernateSession.get(Mbc_session.class, sessionGuid); 
}这个Lambda表达式接收一个hibernateSession参数,并返回一个Mbc_session对象。根据Java的函数式接口定义:
因此,getMBCSessionByGuid方法实际调用的是接受Function<Session, Mbc_session>作为参数的withSession重载方法,而不是接受Consumer<Session>的重载。
而原始的模拟配置:
doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Consumer.class));
错误地指示Mockito对接受Consumer参数的withSession方法调用真实实现。由于实际调用的是Function版本,Mockito的模拟规则并未匹配,导致withSession的Function版本被默认行为(通常是返回null或空值)所覆盖,从而跳过了Lambda内部的真实逻辑。
要解决这个问题,我们需要确保Mockito对正确的方法重载调用真实实现。只需将模拟配置中的Consumer.class替换为Function.class即可:
// 在initMocks或@Before方法中进行配置
public static void initMocks(Session session) { 
  HibernateSessionManager.current = mock(HibernateSessionManager.class, Mockito.RETURNS_DEEP_STUBS); 
  HibernateTransactionManager.current = mock(HibernateTransactionManager.class, Mockito.RETURNS_DEEP_STUBS); 
  // 移除对Consumer版本的模拟(如果存在)
  // doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Consumer.class)); 
  // 正确地对Function版本的withSession调用真实方法
  doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Function.class)); 
  when(HibernateSessionManager.current.getSession()).thenReturn(session); 
} 通过这一修改,当getMBCSessionByGuid方法调用HibernateSessionManager.current.withSession并传入一个Function时,Mockito会匹配到正确的模拟规则,执行withSession的真实逻辑。这将导致Lambda表达式hibernateSession -> { return hibernateSession.get(Mbc_session.class, sessionGuid); }被执行,进而调用模拟的session.get方法,从而达到预期的代码覆盖率和测试行为。
在Mockito中模拟包含函数式接口参数的重载方法时,精确匹配方法签名至关重要。通过理解Consumer和Function等函数式接口的语义差异,并使用any(Function.class)等匹配器,我们可以确保doCallRealMethod()正确作用于目标方法,从而使Lambda表达式内部的逻辑得以执行,实现完整的测试覆盖和准确的单元测试。
以上就是深入理解Mockito:正确模拟带内部方法的静态类函数的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号