PhalconPHP MVC Micro应用程序:指定请求路径并断言响应代码


PhalconPHP MVC Micro app: Specify a request path and assert the response code

我遵循了单元测试教程,并根据这篇文章对其进行了修改,以测试对Micro MVC应用程序的HTTP请求。我可以成功地验证输出字符串,但我不确定如何断言响应状态代码或更改请求路径。

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();

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);
    }
}

好消息和坏消息。好:只要你使用标准的调度原则,你就会得到一个包含你需要的信息的响应。小技巧–当状态为成功时,标头设置为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)进行断言来对所有协同工作的内容进行最终测试。