使用Dart的shelf_rest进行单元测试

3

我正在尝试测试一个运行在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端点进行单元测试?我想运行一些基本测试,例如:

  • GET /accounts/123 返回200
  • GET /accounts/bogus 返回404
1个回答

3

要创建一个单元测试(即无需运行服务器), 您需要将 myRoutermain 函数中拆分出来,并将其放入 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"}));
  });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接