0

我正在尝试创建一些简单的单元测试,这是代码:

import 'dart:io';

import 'package:unittest/unittest.dart';

void main() {
  test('check if sent data equals expected data', () {

    HttpServer.bind('127.0.0.1', 8080)
      .then(expectAsync1((HttpServer server) {
        server.listen((HttpRequest request) {
          expect(request.runtimeType.toString(), equals('_HttpRequest'));
          request.fold(new BytesBuilder(), (prev, next) {
            prev.addAll(next);
            return prev;
          })
          .then(expectAsync1((BytesBuilder bb) {
            var bytes = bb.takeBytes(),
                helloString = new String.fromCharCodes(bytes);
            expect(helloString, equals('hello'));
            request.response.write(helloString);
            request.response.close();
            server.close();
          }));
        });
      }));

    HttpClient client = new HttpClient();
    client.get('127.0.0.1', 8080, '/')
      .then((HttpClientRequest request) {
        request.add('hello'.codeUnits);
        return request.close();
      });

  });
}

给我一个错误:打破异常:'dart:async/stream_impl.dart':断言失败:第 149 行 pos 12:'!_isClosed' 不正确。

经过一些解决方法后,我发现负责的人是request.add('hello'.codeUnits)

所以现在我无法将数据添加到HttpClientRequest. 任何解决方法?

4

1 回答 1

2

你用的是什么版本的 Dart?我无法重现您收到的错误。有关此问题的进展,请参阅http://dartbug.com/13293

但是代码有很多问题:

  1. BytesBuilder 没有 addAll 方法
  2. 使用 client.get 时请求的内容长度设置为 0
  3. 似乎客户端可能会在绑定服务器之前连接。

像下面这样重写测试使其运行:

import 'dart:io';
import 'package:unittest/unittest.dart';

void main() {
  test('check if sent data equals expected data', () {
    expect(HttpServer.bind('127.0.0.1', 8081).then((HttpServer server) {
      HttpClient client = new HttpClient();
      server.listen((HttpRequest request) {
        expect(request.runtimeType.toString(), equals('_HttpRequest'));
        request.fold(new BytesBuilder(), (prev, next) {
          prev.add(next);
          return prev;
        }).then((BytesBuilder bb) {
          var bytes = bb.takeBytes();
          var helloString = new String.fromCharCodes(bytes);
          expect(helloString, equals('hello'));
          request.response.write(helloString);
          request.response.close();
          server.close();
        });
      });

      return client.post('127.0.0.1', 8081, '/').then((HttpClientRequest request) {
        request.add('hello'.codeUnits);
        return request.close().then((HttpClientRequest response) {
          return response.statusCode;
        });
      }).whenComplete(client.close());
    }), completion(equals(HttpStatus.OK)));
  });
}
于 2013-09-13T09:00:45.077 回答