2016-11-29 69 views
2

我想用PHPUnit測試我的Slim應用程序的端點。我努力模擬POST請求,因爲請求主體總是空的。用PHPUnit模擬Slim端點POST請求

  • 我試過這裏描述的方法:Slim Framework endpoint unit testing。 (添加環境變量slim-input
  • 我試着寫php://input直接,但我發現了php://input是隻讀的(艱難地)

環境的仿真工作正常,例如REQUEST_URI始終如預期。我發現請求的正文是從php://inputSlim\Http\RequestBody中讀出的。

注:

  • 我想避免直接調用控制器方法,這樣我就可以檢驗一切,包括端點。
  • 我想避免guzzle,因爲它發送一個實際的請求。我不想在測試應用程序時運行服務器。

我的測試代碼至今:

//inherits from Slim/App 
$this->app = new SyncApiApp(); 

// write json to //temp, does not work 
$tmp_handle = fopen('php://temp', 'w+'); 
fwrite($tmp_handle, $json); 
rewind($tmp_handle); 
fclose($tmp_handle); 

//override environment 
$this->app->container["environment"] = 
    Environment::mock(
     [ 
      'REQUEST_METHOD' => 'POST', 
      'REQUEST_URI' => '/1.0/' . $relativeLink, 
      'slim.input' => $json, 
      'SERVER_NAME' => 'localhost', 
      'CONTENT_TYPE' => 'application/json;charset=utf8' 
     ] 
    ); 

//run the application 
$response = $this->app->run(); 
//result: the correct endpoint is reached, but $request->getBody() is empty 

整個項目(要知道,我已經簡化計算器上的代碼): https://github.com/famoser/SyncApi/blob/master/Famoser.SyncApi.Webpage/tests/Famoser/SyncApi/Tests/

注2: 我問過的slimframework論壇,鏈接: http://discourse.slimframework.com/t/mock-slim-endpoint-post-requests-with-phpunit/973。我會保持stackoverflow和discourse.slimframework最新發生的事情。

注3: 有這個功能,我的一個當前打開的拉請求:https://github.com/slimphp/Slim/pull/2086

+1

爲什麼不直接使用z.b.發送POST請求然後Gu?? – Tebe

+0

我改變了我的問題的標題。我想用PHPUnit來測試端點 –

+0

您能否給我們一個示例端點和測試?我不確定你提供的代碼試圖做什麼。 – nerdlyist

回答

0

有在http://discourse.slimframework.com/t/mock-slim-endpoint-post-requests-with-phpunit/973/7幫助了,解決辦法是從頭開始創建Request和寫入請求主體。

//setup environment vals to create request 
$env = Environment::mock(); 
$uri = Uri::createFromString('/1.0/' . $relativeLink); 
$headers = Headers::createFromEnvironment($env); 
$cookies = []; 
$serverParams = $env->all(); 
$body = new RequestBody(); 
$uploadedFiles = UploadedFile::createFromEnvironment($env); 
$request = new Request('POST', $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); 

//write request data 
$request->write(json_encode([ 'key' => 'val' ])); 
$request->getBody()->rewind(); 
//set method & content type 
$request = $request->withHeader('Content-Type', 'application/json'); 
$request = $request->withMethod('POST'); 

//execute request 
$app = new App(); 
$resOut = $app($request, new Response()); 
$resOut->getBody()->rewind(); 

$this->assertEquals('full response text', $resOut->getBody()->getContents()); 

原來的博客文章這有助於回答在http://glenneggleton.com/page/slim-unit-testing