使用Mockito stub reauthenticateWithCredential时出现MissingStubError求助
问题原因
- Mockito默认使用严格的参数相等匹配来触发stub,你在设置stub时传入的是新创建的
MockAuthCredential实例,而实际测试运行时传入的是另一个AuthCredential实例,两个实例没有重写==和hashCode的情况下会被判定为不相等,因此无法匹配到已设置的stub,触发MissingStubError。
解决方案
方案1:使用任意参数匹配器(无需校验传入参数时使用)
如果你的测试场景不需要校验reauthenticateWithCredential传入的参数具体值,直接用Mockito的any匹配器匹配所有该类型的参数即可:
when(user.reauthenticateWithCredential(any<AuthCredential>())).thenAnswer((_) async => MockUserCredential());
如果是空安全版本的Mockito,需要确保已经导入匹配器相关的扩展,部分版本可能需要搭配isA<AuthCredential>()使用。
方案2:自定义参数匹配规则(需要校验传入参数时使用)
如果你的测试需要验证传入的AuthCredential属性是否符合预期,可以用argThat实现自定义匹配逻辑:
when(user.reauthenticateWithCredential( argThat( (AuthCredential cred) => cred.providerId == 'password' && cred.signInMethod == 'password' ) )).thenAnswer((_) async => MockUserCredential());
如果需要固定匹配某个特定实例,可以给AuthCredential类重写==和hashCode方法,让相同属性的实例被判定为相等。
额外排查项
- 确认stub设置的执行顺序早于被测试代码中
reauthenticateWithCredential的调用时机,不要先调用方法再设置stub - 确认通过locator获取到的
User实例就是你预先注册的MockUser实例,没有出现重复注册覆盖、实例不一致的问题 - 确认
MockUser是通过Mockito的代码生成工具生成的,不是手动编写的未正确实现方法的模拟类
内容的提问来源于stack exchange,提问作者Patttt
相关产品推荐
相关产品推荐

