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

Mockito测试thenAnswer参数类型不匹配,求正确函数语法

解决Mockito thenAnswer语法错误

你遇到的错误是因为thenAnswer的参数类型不匹配:你传入的是直接返回Future<User>的函数,但当前Mockito版本要求传入的是接收Invocation后返回无参异步函数的回调(类型为Future<User> Function() Function(Invocation))。

修改后的正确代码

test(
  "GIVEN success call WHEN login called THEN return User",
  () async {
    //arrange
    when(
      () => service.login(credentials: credential),
    ).thenAnswer(
      (_) => () async => user,
    );

    //act
    final futureUser = await service.login(
      credentials: credential,
    );

    //assert
    expect(futureUser, user);
  },
);

关键说明

  • 原代码中(_) async => Future.value(user)直接返回了Future<User>,不符合thenAnswer的参数要求
  • 修改为(_) => () async => user后,回调函数接收Invocation参数,返回一个无参的异步函数,该函数最终返回目标User对象(async关键字会自动将返回值包装为Future)
  • 也可以用(_) => () => Future.value(user)实现同样效果,两种写法等价

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:40:25