如何在测试时调试控制器,使用:Guzzle,Symfony,PhpUnit,PhpStorm,REST?

时间:2018-01-30 10:25:54

标签: symfony debugging phpunit phpstorm guzzle

在PhpStorm中调试测试类(PHPUnit_Framework_TestCase的子类)时,它会停止在此类中设置的断点,但不会停止在请求指向的控制器(Symfony)中。

//test class - here debugger stops
class FooControllerTest extends \PHPUnit_Framework_TestCase
{
    public function testPOST()
    {
        $response = $this->client->post('/api/foo', [
           'body' => json_encode($data)
        ]);

//controller - here debugger not stopping
/**
 * @Route("/api/foo")
 * @Method("POST")
 */
public function newAction(Request $request)
{
    //...
    return new Response($json, 201, array(
        'Content-Type' => 'application/json'
    ));

请求肯定会进入此控制器,因为我可以在那里更改http代码,这个更改在client->post(行之后的测试类中是可读的

如何在测试时调试控制器?

2 个答案:

答案 0 :(得分:0)

如果您正在使用Symfony和PHPUnit测试您的api,我可以给您一些建议,前提是我没有真正完全理解“调试控制器”的含义。

首先:当测试失败时,将一个侦听器附加到将打印PSR-7 HTTP请求和响应主体的PHPUnit。如果你使用的是Guzzle 6,那很容易实现。以下是一些可以帮助您的文档:

第二:在config_test.yml中启用探查器。这样,探查器将收集测试信息,并使您的调试更容易。由于您正在打印Psr7请求和响应字符串,因此标题将包含指向该请求的探查器的链接。

使用SQLite数据库进行测试设置,我发现它非常有用。现在,如果你真的想跳到下一个级别,你应该使用Behat。 :)

答案 1 :(得分:0)

在PhpStrom中,您需要准备Simultaneous debugging sessions。因此,在您的情况下,在Test类中将GET参数添加到URL:

class FooControllerTest extends \PHPUnit_Framework_TestCase
{
    public function testPOST()
    {
        //...
        $response = $this->client->post('/api/foo'. '?' . $this->getDebugQuery(), [
            'body' => json_encode($data)
        ]);
        //...

    }

    private function getDebugQuery()
    {
        $debuggingQuerystring = '';
        if (isset($_GET['XDEBUG_SESSION_START'])) { // xdebug
            $debuggingQuerystring = 'XDEBUG_SESSION_START=' . $_GET['XDEBUG_SESSION_START'];
        }
        if (isset($_COOKIE['XDEBUG_SESSION'])) { // xdebug (cookie)
            $debuggingQuerystring = 'XDEBUG_SESSION_START=PHPSTORM';
        }
        if (isset($_GET['start_debug'])) { // zend debugger
            $debuggingQuerystring = 'start_debug=' . $_GET['start_debug'];
        }
        if (empty($debuggingQuerystring)) {
            $debuggingQuerystring = 'XDEBUG_SESSION_START=PHPSTORM';
        }

        return $debuggingQuerystring;
    }

并切换“Listen debugger connections”按钮。