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

How to debug controller while testing, using: Guzzle, Symfony, PhpUnit, PhpStorm, REST?

在 PhpStorm 中调试测试 class(PHPUnit_Framework_TestCase 的子 class)时,它会在此 class 中设置的断点处停止,但不会在控制器中停止( 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(

之后的测试 class 中是可读的

如何边测试边调试controller?

如果您正在使用 Symfony 和 PHPUnit 测试您的 api,我可以给您一些建议,前提是我并不真正完全理解您所说的 [=28] =].

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

其次:在您的 config_test.yml 中启用探查器。这样,探查器将为您的测试收集信息,并使您的调试更容易。由于您正在打印 Psr7 请求和响应字符串,因此 headers 将为该请求的分析器包含一个 link。

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

在 PhpStorm 中您需要准备 Simultaneous debugging sessions。因此,在您的情况下,在 Test class 中将 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;
    }

并切换“侦听调试器连接”按钮。