我有一个 Dart 类,我想对其进行单元测试,并且我想模拟对 dart:html 库的调用,以确保我的类的行为符合预期。我已经查看了Mocking with Dart的文章,但它没有提到如何模拟 HTML 库。有人有建议吗?
问问题
279 次
1 回答
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;
}
于 2012-11-03T11:14:18.673 回答