使用 dart 进行单元测试 shelf_rest

Unit testing with dart's shelf_rest

我正在尝试在 shelf_rest 上测试 Dart REST 应用 运行。假设设置类似于 shelf_rest 示例,如何在不实际 运行 连接 HTTP 服务器的情况下测试配置的路由?

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_rest/shelf_rest.dart';

void main() {
  var myRouter = router()
    ..get('/accounts/{accountId}', (Request request) {
      var account = new Account.build(accountId: getPathParameter(request, 'accountId'));
      return new Response.ok(JSON.encode(account));
    });

  io.serve(myRouter.handler, 'localhost', 8080);
}

class Account {
  final String accountId;

  Account.build({this.accountId});

  Account.fromJson(Map json) : this.accountId = json['accountId'];

  Map toJson() => {'accountId': accountId};
}  

class AccountResource {
  @Get('{accountId}')
  Account find(String accountId) => new Account.build(accountId: accountId);
}

在不涉及太多额外逻辑的情况下,如何对 GET account 端点进行单元测试?我想 运行 进行的一些基本测试是:

要创建单元测试(即没有 运行 服务器),则需要在 main 函数之外拆分 myRouter 并将其放入 lib目录。例如

import 'dart:convert';

import 'package:shelf/shelf.dart';
import 'package:shelf_rest/shelf_rest.dart';

var myRouter = router()
  ..get('/accounts/{accountId}', (Request request) {
    var account =
        new Account.build(accountId: getPathParameter(request, 'accountId'));
    return new Response.ok(JSON.encode(account));
  });

class Account {
  final String accountId;

  Account.build({this.accountId});

  Account.fromJson(Map json) : this.accountId = json['accountId'];

  Map toJson() => {'accountId': accountId};
}

然后在test目录下创建一个测试文件,像

一样测试
import 'package:soQshelf_rest/my_router.dart';
import 'package:test/test.dart';
import 'package:shelf/shelf.dart';
import 'dart:convert';

main() {
  test('/account/{accountId} should return expected response', () async {
    final Handler handler = myRouter.handler;
    final Response response = await handler(
        new Request('GET', Uri.parse('http://localhost:9999/accounts/123')));
    expect(response.statusCode, equals(200));
    expect(JSON.decode(await response.readAsString()),
        equals({"accountId": "123"}));
  });
}