why flutter test coverage does not cover assert statements?

Issue

I have a constructor for LoginPageBloc as shown below

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

when I use flutter test –coverage, the assertion statements are excluded. why??

Then I checked on the dart-lang repo for any open issues, and I found this.

This coverall result also shows the same issue (found in that git repo issue).

But, that issue status is closed and I found the following message thereby @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.

I having difficulty understanding the above message by @ZichangG.

Unfortunately, I am still experiencing the same problem.
Just because of these assertion statements, I am unable to reach 100% code coverage.

why flutter test coverage does not cover assert statements?

Could you please explain to me the reason behind this and what should I do to avoid this?

Solution

You can wrap the assert call into a until function to by pass the issue.

See below,

Define a util function

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

Use it like

 assertNotNull(dataRepository);

Answered By – Code Wizard

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.