我已按照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);
}
}
感謝您的回覆!我一定會借用你的'assertResponseCode'函數。你有沒有想法如何設置'$ mockRequest'中的'$ path',以便它能夠正確路由? – 2014-09-10 19:13:58
你可以模擬請求的[getURI](https://github.com/phalcon/cphalcon/blob/master/ext/http/request.c#L1222)方法,但它會更容易,也許更好地直接更改' $ _SERVER ['REQUEST_URI']',這是Phalcon在內部使用的。 – 2014-09-11 16:30:01
謝謝,但它沒有奏效。我有什麼需要包含'ResponseHeaders'? Phalcon \ Http \ Response \ Headers似乎沒有任何常數。另外'$ _SERVER ['REQUEST_URI']'也不適用於我,不管怎麼說,一切都進入索引 – 2014-09-11 20:34:24