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

使用Mockito的any参数匹配器存根方法时遇类型错误咨询

Mockito中any参数匹配器类型不匹配问题解决

问题重现

你的代码示例:

class Foo {
  int bar(int x) => x;
}

class MockFoo extends Mock implements Foo {}

void main() {
  final foo = MockFoo();
  when(foo.bar(any)).thenReturn(42);
  print(foo.bar(7)); // 预期输出42
}

运行时触发类型错误:

The argument type 'Null' can't be assigned to the parameter type 'int'.dart(argument_type_not_assignable)

问题原因

any默认返回Null类型,而bar方法要求传入非空的int类型参数,Dart的强类型检查会直接拦截这种类型不匹配的情况,导致编译报错。

解决方法

有两种简单有效的修复方式:

1. 使用带泛型类型的any<int>()

给any指定具体的泛型类型,让匹配器返回符合要求的int类型,代码修改如下:

void main() {
  final foo = MockFoo();
  when(foo.bar(any<int>())).thenReturn(42);
  print(foo.bar(7)); // 输出42
}

2. 使用argThat配合类型匹配器

如果需要更灵活的匹配逻辑,可以用argThat结合isA<int>()来匹配任意int类型参数:

void main() {
  final foo = MockFoo();
  when(foo.bar(argThat(isA<int>()))).thenReturn(42);
  print(foo.bar(7)); // 输出42
}

补充说明

Mockito的参数匹配器必须和被Mock方法的参数类型兼容,当方法参数是非空的具体类型时,一定要使用带类型约束的匹配器,才能绕过Dart的类型检查并正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:34:58