我有一个Dart类,我想进行单元测试,我想模拟对dart:html库的调用,以确保我的类按预期运行。我查看了Mocking with Dart的文章,但没有提到如何模拟HTML库。有没有人有任何建议?
答案 0 :(得分:1)
这不容易实现,因为 dart:html 库不是无头的(即需要浏览器)。我通常尝试遵循MVP设计模式,以确保与DOM交互的代码仅在我的视图类中,并且所有商业逻辑都在演示者中。这样我就可以在不需要访问DOM API的情况下对演示者进行单元测试。下面列出了一个小例子。
// view interface has no reference to dart:html
abstract class View {
hello();
}
// view impl uses dart:html but hands of all logic to the presenter
class ViewImpl implements View {
View(this._presenter) {
var link = new Element.html("<a href="">a link</a>");
link.on.click.add(_presenter.onClick());
body.nodes.add(link);
}
hello() {
body.nodes.add(new Element.html("<p>Hello from presenter</p>");
}
Presenter _presenter;
}
// presenter acts on the View interface and can therefor be tested with a mock.
class Presenter {
Presenter(this._view);
onClick() => _view.hello();
View _view;
}