How to test a private function, in Dart?

我的未来我决定 提交于 2019-12-08 14:44:26

问题


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?


回答1:


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
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.




回答2:


Several people believe we shouldn't test private directly: it should be tested through the public interface.

An advantage of following this guidance, is that your test won't depend on your implementation. Said differently: if you want to change your private without changing what you expose to the world, then you won't have to touch your tests.

According to this school of though, if your private is important enough to justify a unit test, then it might make sense to extract it in a new class.

Putting all this together, what you could do here, is:

  • Create a kind of helper class with this hello method as public. You can then easily unit test it
  • Let your current class use an instance of this helper class
  • Test the public methods of your current class which relies on _hello: if this private has a bug, it should be catch by those higher level tests


来源:https://stackoverflow.com/questions/21657315/how-to-test-a-private-function-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!