2017-03-16 5 views
2

shelf_restで動作するダーツRESTアプリをテストしようとしています。 shelf_restの例と似たセットアップを仮定すると、実際にHTTPサーバーを実行せずに構成されたルートをどのようにテストできますか?あまりにも多くの追加のロジックに得ることなくダーツのshelf_restによるユニットテスト

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

答えて

2

を返し、その後、あなたは分割する必要がありますmyRoutermainの外に置き、ファイルlib dirに入れてください。例えば

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}; 
} 

はその後

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"})); 
    }); 
} 
のようなテスト testディレクトリ内のファイルやテストを作成します
関連する問題