2017-03-16 58 views
2

我試圖測試在shelf_rest上運行的DART REST應用程序。假設類似於shelf_rest示例的設置,如何在不實際運行HTTP服務器的情況下測試配置的路由?使用dart的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

要(沒有正在運行的服務器即)創建單元測試,那麼你需要拆分myRouter以外的main函數,並把它放在lib目錄中的一個文件中。 e.g

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