Dart、单元测试和一般异步编程的新手。和 StackOverflow,就此而言。尝试围绕shelf_route 构建一个RESTful 服务器并使用HttpClient 对其进行测试。
我的测试有效,但它们不会自行退出。相反,我必须手动终止该过程。我尝试了几种我在网上找到的方法,但没有运气。谁能帮我一把?这是我正在使用的:
import 'dart:io';
import 'package:unittest/unittest.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'package:toner_track/handlers.dart';
import 'package:toner_track/config.dart';
void main() {
var server;
group('Server tests', () {
var server;
setUp(() {
var handler = const shelf.Pipeline().addHandler(router);
io.serve(handler, HOST, PORT).then((s) {
server = s;
});
});
tearDown(() {
server.close();
});
test('Invalid URL returns 404', () {
new HttpClient().getUrl(Uri.parse('http://$HOST:$PORT'))
.then((HttpClientRequest request) => request.close())
.then(expectAsync((HttpClientResponse response) {
expect(response.statusCode, equals(404));
}));
});
test('GET /printers returns 200', () {
new HttpClient().getUrl(Uri.parse('http://$HOST:$PORT$rootPrintersPath'))
.then((HttpClientRequest request) => request.close())
.then(expectAsync((HttpClientResponse response) {
expect(response.statusCode, equals(200));
}));
});
test('POST /printers returns 201', () {
new HttpClient().postUrl(Uri.parse('http://$HOST:$PORT$rootPrintersPath'))
.then((HttpClientRequest request) {
request.write('{"foo": 42}');
return request.close();
})
.then(expectAsync((HttpClientResponse response) {
expect(response.statusCode, equals(201));
}));
});
});
}
更新:决定放弃 HttpClient 以支持该http
包。更容易使用,我的测试现在自行终止。显然,我在第一次复飞时没有正确处理某些事情。这是上面的代码现在的样子:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:unittest/unittest.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'package:toner_track/handlers.dart';
import 'package:toner_track/config.dart';
void main() {
group('Server tests', () {
var server;
setUp(() {
var handler = const shelf.Pipeline().addHandler(router);
return io.serve(handler, HOST, PORT).then((s) {
server = s;
});
});
tearDown(() {
server.close();
});
test('Invalid URL returns 404', () {
http.get('http://$HOST:$PORT').then(expectAsync((response) {
expect(response.statusCode, equals(404));
}));
});
test('GET /printers returns 200', () {
http.get('http://$HOST:$PORT$rootPrintersPath').then(expectAsync((response) {
expect(response.statusCode, equals(200));
}));
});
test('POST /printers returns 201', () {
http.post('http://$HOST:$PORT$rootPrintersPath', body: {"foo": "42"}).then(expectAsync((response) {
expect(response.statusCode, equals(201));
}));
});
});
}