3

I am interested in a simple approach to test library private classes/functions. There are two files below meant to test code in the file curves_attribution.dart. The latter (2) is the suggested approach described in http://pub.dartlang.org/doc/package-layout.html. The downside to that is you have no access to private library scoped items. A simple solution to test library scoped items is to include tests in the library itself. The implications of this are that any includes required by (1) must be added to the library finance.dart, but they are required only for the purpose of testing. So, for example, unittest.dart would be imported.

I've tried this setup by accessing the tests successfully with http://pub.dartlang.org/packages/hop. Is it realistic to expect to be able to ship apps that have 0 testing code included due to tree-shaking?

If not suggestions for other approaches to testing library private code welcome. If this is a bad idea for other reasons, please explain.

|-- lib
|   |-- finance.dart
|   |-- src
|   |   |-- finance
|   |   |   |-- curves_attribution.dart
|   |   |   |-- test_curves_attribution.dart (1)
|   |-- test
|   |   |-- test_curves_attribution_public.dart (2)
user1338952
  • 3,233
  • 2
  • 27
  • 41

2 Answers2

3

Unless you use mirrors, you can expect that the tree-shaker eliminates all testing code. It slightly depends on how you write your test-code though.

The tree-shaking algorithm is bullet-proof to exclude unused static methods or classes. It might not be able to remove all unused instance members of instantiated classes, though.

As example for code that might not be tree-shaked:

class A {
  test() {...}  // Actually used in code. Not just for testing.
}
class B {  // Class B is used in program.
  test() {...}  // Only supposed to be used for testing.
}

If the program contains an o.test(), where the compiler is not completely sure what o is, it will include both A.test() and B.test().

Florian Loitsch
  • 7,698
  • 25
  • 30
1

You could use this Compile-time dead code elimination with dart2js to break dependencies if you have any that prevent tree-shaking.

log(String msg) {
  if (const String.fromEnvironment('DEBUG') != null) {
    print('debug: $msg');
  }
}

main() {
  log('In production, I do not exist');
}

Another approach is discussed here dart, unit testing private methods

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567