I've followed the unit testing tutorial and modified it to test a HTTP request to Micro MVC app, based on this post. I can successfully validate the output string, however I'm not sure how to assert the response status code or change the request path.
index.php
<?php
$app = new PhalconMvcMicro();
#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();
tests/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);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…