2014-09-10 17 views
2

我已按照unit testing tutorial並將其修改爲測試對Micro MVC應用程序的基於on this post的HTTP請求。我可以成功驗證輸出字符串,但是我不確定如何聲明響應狀態碼或更改請求路徑。PhalconPHP MVC微應用程序:指定請求路徑並聲明響應代碼

的index.php

<?php 

$app = new \Phalcon\Mvc\Micro(); 

#Default handler for 404 
$app->notFound(function() use ($app) { 
    $app->response->setStatusCode(404, "Not Found")->sendHeaders(); 
}); 

$app->post('/api/robots', function() use ($app) { 
    //Parse JSON as an object 
    $robot = $app->request->getJsonRawBody(); 
    //Build the response 
    $app->response->setJsonContent($robot); 
    return $app->response; 
}); 

$app->get('/', function() { 
    echo 'Hello'; 
}); 

$app->handle(); 

測試/ UnitTest.php中

class MvcMicroUnitTest extends \UnitTestCase { 

    public function testNotFound() { 
     $path = '/invalid'; 
     $mockRequest = $this->getMock("\\Phalcon\\Http\\Request"); 
     //TODO: Set an invalid URL $path in the mock 
     $this->di->set('request', $mockRequest, true); 
     include("../index.php"); 
     //TODO: Assert status is 404 
     $this->expectOutputString(''); 
    } 

    public function testPostRobot() { 
     $rawJson = '{"name":"C-3PO","type":"droid","year":1977}'; 
     $path = '/api/robots'; 
     $mockRequest = $this->getMock("\\Phalcon\\Http\\Request", array(
      "getJsonRawBody")); 
     $mockRequest->expects($this->any()) 
       ->method("getRawBody") 
       ->will($this->returnValue($rawJson)); 
     //TODO: Set the $path in the mock 
     $this->di->set('request', $mockRequest, true); 
     include("../index.php"); 
     //TODO: Assert status is 200 
     $this->expectOutputString($rawJson); 
    } 
} 

回答

1

好消息和壞消息。好:就您使用標準調度原則而言,您將得到一個響應,其中包含您需要的信息。小竅門 - 當狀態成功時,標題設置爲false

/** 
* @param $expected 
* @throws ExpectationFailedException 
* @return $this 
*/ 
protected function assertResponseCode($expected) 
{ 
    $actual = $this->di->getResponse()->getHeaders()->get('Status'); 

    if ($actual !== false && $expected !== 200 && !preg_match(sprintf('/^%s/', $expected), $actual)) { 
     throw new ExpectationFailedException(sprintf('Failed asserting that response code is "%s".', $expected)); 
    } 

    $this->assertTrue(true); 
    return $this; 
} 

不好:你這樣做是錯誤的。這是功能/驗收測試領域,有一個叫做Behat的神話般的框架。你應該做你自己的研究,但實質上,雖然PHPUnit擅長測試更多或更少的獨立功能塊,但它會在測試更大的事情時感到厭倦,比如完整的請求執行。之後,您將開始遇到會話錯誤,配置錯誤的環境等問題,所有這些都是因爲每個請求都應該在它自己的獨立空間中執行,而您迫使它做相反的事情。另一方面,Behat以一種完全不同的方式工作,對於每個場景(發佈機器人,查看不存在的頁面),它會向服務器發送一個新的請求並檢查結果。它主要用於通過對最終結果(響應對象/ html/json)進行斷言來一起工作的最終測試。

+0

感謝您的回覆!我一定會借用你的'assertResponseCode'函數。你有沒有想法如何設置'$ mockRequest'中的'$ path',以便它能夠正確路由? – 2014-09-10 19:13:58

+0

你可以模擬請求的[getURI](https://github.com/phalcon/cphalcon/blob/master/ext/http/request.c#L1222)方法,但它會更容易,也許更好地直接更改' $ _SERVER ['REQUEST_URI']',這是Phalcon在內部使用的。 – 2014-09-11 16:30:01

+0

謝謝,但它沒有奏效。我有什麼需要包含'ResponseHeaders'? Phalcon \ Http \ Response \ Headers似乎沒有任何常數。另外'$ _SERVER ['REQUEST_URI']'也不適用於我,不管怎麼說,一切都進入索引 – 2014-09-11 20:34:24

相關問題