为什么 flutter 测试覆盖率不包括 assert 语句?

why flutter test coverage does not cover assert statements?

我有一个 LoginPageBloc 的构造函数,如下所示

 LoginPageBloc(
  {@required this.dataRepository,
 })
  : assert(null != dataRepository);

当我使用 flutter test --coverage 时,断言语句被排除在外。为什么??

然后我检查了 dart-lang 仓库是否有任何未解决的问题,我发现 this

This 总体结果也显示了相同的问题(在 git 回购问题中发现)。

但是,该问题状态已关闭,我通过@ZichangG 找到了以下消息。

VM uses function calls to determine. Callsites that have been executed will be considered as a hit.

If a variable is evaluated, like assert(mode == null), an implicit getter function will be called if it is not a local variable. For this case assert(callback != null), callback is a local variable and it is also not being called here.

When functions that has been executed are evaluated, we set the first token position of that function as a hit. That's probably the reason why a line like assert( () { will be marked as hit. Because the closure function starts in this line.

我很难理解@ZichangG 的上述消息。

不幸的是,我仍然遇到同样的问题。 仅仅因为这些断言语句,我无法达到 100% 的代码覆盖率。

为什么flutter测试覆盖率不覆盖assert语句?

能否请您解释一下这背后的原因以及我应该怎么做才能避免这种情况?

您可以将 assert 调用包装到 until 函数中以绕过问题。

见下文,

定义一个 util 函数

  void assertNotNull(Object object) {
    assert(object != null);
    }

像这样使用

 assertNotNull(dataRepository);