gpt4 book ai didi

unit-testing - 使用 dart 的 shelf_rest 进行单元测试

转载 作者:行者123 更新时间:2023-12-03 02:57:08 27 4
gpt4 key购买 nike

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

最佳答案

要创建单元测试(即没有正在运行的服务器),您需要在 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"}));
});
}

关于unit-testing - 使用 dart 的 shelf_rest 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com