【问题标题】:how to setup a unittest for a web-project如何为 web 项目设置单元测试
【发布时间】:2015-01-31 17:44:10
【问题描述】:

我在 DartEditor(1.8.5) 中正确配置我的第一个单元测试时遇到问题。

我用 Dart 编写了一个 web 应用程序,它位于 web 文件夹中。 现在我添加了一个与 web 平行的测试文件夹,其中包含一个名为 test.dart 的文件:

library dartingflame_test;

import 'dart:math';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';
import 'package:mockito/mockito.dart';
import '../web/dartingflame.dart';

void main() {
  useHtmlConfiguration();

  test("verify robot's direction after move", verifyRobotDirectionAfterMove);
}

void verifyRobotDirectionAfterMove() {...}

很遗憾,我现在无法运行此测试文件。

  • Run with Dartium 导致消息:Unable to locate associated html file
  • 运行导致:Observatory listening on http://127.0.0.1:49919 The built-in library 'dart:html' is not available on the stand-alone VM. 'package:unittest/html_config.dart': error: line 10 pos 1: library handler failed import 'dart:html';

使用useVMConfiguration() 而不是useHtmlConfiguration() 没有帮助。测试执行仍然抱怨被测库中的import 'dart:html';-line。

我在"Unit Testing with Dart"-文章中找不到解决方案。

更新(包含 Günter Zöchbauer 的评论)

好的,我创建了调用 test.dart 的 index.html,但现在我似乎对被测库 import '../web/dartingflame.dart'; 的相对导入有问题:

Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8081/web/dartingflame.dart
An error occurred loading file: http://localhost:8081

【问题讨论】:

  • 如果你想测试代码,代码应该在lib而不是web,那么你可以使用包导入而不是相对导入。
  • 我的应用程序包含许多在画布上绘制的域对象。为了将这些移动到 lib 到 lib 文件夹,我必须从 CanvasRenderingContext2D 中抽象出来,这是他们重绘方法中的一个参数。虽然这是可能的,但似乎有点矫枉过正。并且必须有一种方法来测试 web 文件夹中的内容,否则 unittest/html_config.dart 文件将没有意义。
  • 我不明白你关于“......必须抽象形式CanvasRenderingContext2D”和unittest/html_config.dart的评论。我看不出为什么代码的位置会对这个主题产生任何影响。没有理由在web 中有代码。唯一需要在 Web 中的是带有 Dart 脚本标签(包含 main)的入口页面 HTML 文件。除了lib之外,从顶级目录(webbinexampletest、...)之外导入文件通常是错误的。当您使用相对导入时,请始终留在您所在的顶级目录中,否则请使用包。
  • 啊,所以测试我的网络代码的问题不是代码导入dart:html,而是代码位于web下?!
  • 我仍然看不出你的代码所在的文件夹与你是否必须抽象或是否导入 dart:html 有什么关系。唯一改变的是 import 语句中的路径。

标签: unit-testing dart dart-editor


【解决方案1】:

您需要创建一个网页index.html,并将测试脚本作为脚本标记,然后像任何 Dart 网络应用程序一样启动它。您也可以使用content_shell 以非交互方式运行它。 Dart SDK 包含一个下载和安装content_shell 的批处理脚本(它被排除在SDK 下载之外以保持合理的下载大小。

http://pub.dartlang.org 还提供了一个包test_runner,它有助于在test 目录中运行所有测试。

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多