Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test dart class static constant?

enter image description here

Here is my test code:

 test('should set correct constant', (){
    expect(Stores.CurrentContext, 'currentContext');
  });

but the picture above shows that the static constant code not tested. and why?

version infos:

Flutter 1.2.2-pre.3 • channel master • https://github.com/flutter/flutter.git
Framework • revision 67cf21577f (4 days ago) • 2019-02-14 23:17:16 -0800
Engine • revision 3757390fa4
Tools • Dart 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)
like image 600
junk Avatar asked Oct 28 '25 07:10

junk


1 Answers

A coverage tool registers which code instructions was accessed by the running code.

Think of it as a recording of the memory addresses of "code sections" visited by the Program Counter register of the processor stepping through program functions.

A static variable is reached through a data memory access, there are no code instructions involved: a variable should be on the stack, on the heap or in a data section if it is a constant.

Consider this code:

import 'package:rxdart/rxdart.dart';

class Stores {
  static const String Login = 'login';
  static const String CurrentContext = 'currentContext';
}

class Store {
  final name;

  static var eMap = Map();

  Store._internal(this.name);     // DA:13

  factory Store(String name) {    // DA:15
    if (eMap.containsKey(name)) { // DA:16
      return eMap[name];          // DA:17
    } else {
      final store = Store._internal(name);  // DA:19
      eMap[name] = store;                   // DA:20
      return store;
    }

  }

}

and this code run:

test('should set correct constant', (){
  Store('currentContext');
  Store('currentContext');
  expect(Stores.CurrentContext, 'currentContext');
});

If you look at the raw output of icov you will notice that lines number of static variable is never reached, giving meaning to the model described above:

SF:lib/stores.dart
DA:13,1
DA:15,1
DA:16,2
DA:17,2
DA:19,1
DA:20,2
LF:6
LH:6

The visual reporting tool shows a 100% coverage:

LCOV coverage report

If your reporting tool shows red lines over static variables it has to be considered a "false positive": survive with it or change the reporting tool.

like image 199
attdona Avatar answered Oct 31 '25 02:10

attdona