2

我正在尝试测试在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);
}

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

  • GET /accounts/123返回 200
  • GET /accounts/bogus返回 404
4

1 回答 1

2

要创建单元测试(即没有正在运行的服务器),您需要myRouter在函数之外拆分main并将其放入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"}));
  });
}
于 2017-03-16T06:52:56.777 回答