如何在Dart中测试私有功能? [英] How to test a private function, in Dart?

查看:190
本文介绍了如何在Dart中测试私有功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在dart文件 hello.dart 中定义了一个私有函数:

  _hello(){
返回世界;
}

我想在另一个文件 mytest中对其进行测试。 dart

  library mytest; 

导入‘dart:unittest / unittest.dart’;

main(){
test('test private functions',(){
Expect(_hello(),equals( world));
}
}

但是不幸的是,测试代码无法编译,但是我确实需要测试私有的 _hello 函数。有什么解决方案吗?

解决方案

尽管我同意私有方法/类不应作为测试的一部分,但meta包确实提供了 @visibleForTesting 属性,如果您使用分析器,则会向您发出警告尝试使用其原始库之外的成员或测试。您可以像这样使用它:

  import'package:meta /meta.dart'; 
...
@visibleForTesting
hello(){
return world;
}

您的测试现在可以使用它而不会出现错误或警告,但是如果其他人尝试使用它,则会收到警告。 / p>

同样,执行此操作的智慧是另一回事问题-通常是否值得进行测试,是否值得进行公开测试(或者将通过您的公开界面进行测试,这才是真正重要的事情)。同时,即使对于您的私有方法/类,您可能只想拥有严格的测试或测试驱动的原理,因此-Dart允许您采用这种方式。



编辑添加:如果您正在开发库,并且将导出带有 @visibleForTesting 的文件,则实际上是在添加公共API。有人可以在关闭分析仪的情况下消耗掉它(或者只是忽略警告),如果以后再删除它,可能会损坏它们。


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?

解决方案

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.

这篇关于如何在Dart中测试私有功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆