【问题标题】:Dart Mocking HTML libraryDart 模拟 HTML 库
【发布时间】:2012-10-19 19:46:24
【问题描述】:

我有一个 Dart 类,我想对其进行单元测试,并且我想模拟对 dart:html 库的调用,以确保我的类的行为符合预期。我查看了Mocking with Dart 的文章,但没有提到如何模拟 HTML 库。有人有什么建议吗?

【问题讨论】:

  • dart:html 还包含非 UI 类,例如 localStorage 和 sessionStorage,它们是客户端持久性的基础。我要确保我的数据存储和加载例程正常工作并且不会倒退。我想模拟 Storage 类,但不能因为模拟它,我必须在我的单元测试文件中导入 dart:html。但 Dart 的酒吧系统不允许这样做。相反,它给出了错误:“不知道如何加载'dart:html'”。有没有办法从 dart:html 模拟类而不导入 dart:html(在单元测试中)?

标签: mocking dart


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多