php - PhalconPHP MVC Micro app: Specify a request path and assert the response code -
i've followed unit testing tutorial , modified test http request micro mvc app, based on post. can validate output string, i'm not sure how assert response status code or change request path.
index.php
<?php $app = new \phalcon\mvc\micro(); #default handler 404 $app->notfound(function () use ($app) { $app->response->setstatuscode(404, "not found")->sendheaders(); }); $app->post('/api/robots', function() use ($app) { //parse json object $robot = $app->request->getjsonrawbody(); //build 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 invalid url $path in mock $this->di->set('request', $mockrequest, true); include("../index.php"); //todo: assert status 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 $path in mock $this->di->set('request', $mockrequest, true); include("../index.php"); //todo: assert status 200 $this->expectoutputstring($rawjson); } }
good news , bad news. good: far use standard dispatching principle have response, contain information need. small trick – when status success header set 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 response code "%s".', $expected)); } $this->asserttrue(true); return $this; }
bad: doing wrong way. area of functional / acceptance testing , there fabulous framework called behat. should own research, essentially, while phpunit great @ testing more or less independent blocks of functionality sucks @ testing bigger things full request execution. later start experiencing issues session errors, misconfigured environment, etc., because each request supposed executed in it's own separate space , force doing opposite. behat on other hand works in different way, each scenario (post robot, view non-existing page), sends fresh request server , checks result. used final testing of working making assertions on final result (response object / html / json).
Comments
Post a Comment