当我尝试测试后HttpRequest时,我不太确定我是否理解发生了什么。这是我班完成这项工作的代码:
import 'dart:html';
class HttpReportAdapter {
var logmaster;
int log_level = 2;
String url;
HttpReportAdapter(this.url) {}
post(r, level) {
var data = {
'message' : r,
'log_level' : log_level.toString(),
};
if(this.logmaster != null)
data['log_level_string'] = this.logmaster.log_level_as_string(level);
return HttpRequest.postFormData(this.url, data);
}
}
这是测试代码:
import '../lib/report_adapters/http_report_adapter.dart';
import "package:test/test.dart";
void main() {
var adapter;
setUp(() {
adapter = new HttpReportAdapter("http://localhost:4567/errors");
});
test("sends an ajax request and acknowledges a 200 response from the server", () {
adapter.post("message", 2).then((_) => print("!!!!!!!!!"));
});
}
现在,正如你所看到的,我甚至没有试图测试任何东西,只是输出一些东西。在运行此过程中,请求确实指向http://localhost:4567/errors
,我可以在服务器的日志中看到它。
但是,!!!!!!!!
未打印。此外,测试失败:
This test failed after it had already completed. Make sure to use
[expectAsync] or the [completes] matcher when testing async code.
但是,如果我在发送响应之前强制服务器睡眠1秒,那么测试就会顺利通过,不会出现错误。
如果有人能帮助我理解这一切,并因此写出正确的测试,我将不胜感激。
您需要返回Future
,以便测试可以等待它完成
return adapter.post("message", 2).then((_) => print("!!!!!!!!!"));
否则,测试将在服务器的响应到达之前完成。