具有空安全性的 Flutter mockito 抛出空类型错误

时间:2021-05-03 09:42:37

标签: flutter mockito flutter-test

我一直在关注这个关于模拟的官方文档有一段时间了。

此测试在运行时抛出错误 type 'Null' is not a subtype of type 'String'

Test with error

当我在 StringString? 更改为 getString() 时,它过去了,我不明白为什么。我无意让函数为空,所以我不需要让它为空。

1 个答案:

答案 0 :(得分:1)

如果你正在使用 mockito null 安全,你必须这样做:

  1. 您需要在main()之前添加@GenerateMocks(["M"]),其中"M"将是您要创建Mock的类的名称,并且您必须删除'class MMock extends Mock实现 M'
@GenerateMocks(["M"])
void main() {....}
  1. 然后需要导入“import package:mockito/annotations.dart';”

  2. 接下来你必须在你的开发依赖项中安装'build_runner: ^1.11.0',最后你必须运行命令:“flutter pub run build_runner build”,这将创建一个你拥有的Mock文件要使用而不是 MMock,名称将是 'Mockclassname'

您可以在此链接中了解更多信息: https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md

或此视频(此为西班牙语) https://www.youtube.com/watch?v=nWs3gfYF5u8