How to test a private function, in Dart?

dart, dart-unittest

Solution

While I agree that private methods/classes shouldn't be part of your tests, the meta package does provide an `@visibleForTesting` attribute, and the analyzer will give you a warning if you attempt to use the member outside of its original library or a test. You can use it like this:

import 'package:meta/meta.dart';

@visibleForTesting
String hello() {
  return "world";
}

Your tests will now be able to use it without error or warning, but if someone else tries to use it they'll get a warning.

Again, as to the wisdom of doing this is another question - usually if it's something worth testing, it's something that's worth being public (or it'll get tested through your public interfaces and that's what really matters anyway). At the same time, you might just want to have rigorous tests or test driven principles even for your private methods/classes so - Dart lets you this way.

Edit to add: If you're developing a library and your file with `@visibleForTesting` will be exported, you are essentially adding public API. Someone can consume that with the analyzer turned off (or just ignore the warning), and if you remove it later you may break them.

Problem

Say I defined a private function in a dart file `hello.dart`: ``` _hello() { return "world"; } ``` I want to test it in another file `mytest.dart`: ``` library mytest; import 'dart:unittest/unittest.dart'; main() { test('test private functions', () { expect(_hello(), equals("world")); } } ``` But unfortunately, the test code can't be compiled. But I do need to test that private `_hello` function. Is there any solution?

Original source

Related problems