【问题标题】:$response->getBody() is empty when testing Slim 3 routes with PHPUnit使用 PHPUnit 测试 Slim 3 路由时,$response->getBody() 为空
【发布时间】:2016-03-04 20:32:23
【问题描述】:

我使用以下方法在我的 PHPUnit 测试中调度 Slim 应用的路由:

protected function dispatch($path, $method='GET', $data=array())
{
    // Prepare a mock environment
    $env = Environment::mock(array(
        'REQUEST_URI' => $path,
        'REQUEST_METHOD' => $method,
    ));

    // Prepare request and response objects
    $uri = Uri::createFromEnvironment($env);
    $headers = Headers::createFromEnvironment($env);
    $cookies = [];
    $serverParams = $env->all();
    $body = new RequestBody();

    // create request, and set params
    $req = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
    if (!empty($data))
        $req = $req->withParsedBody($data);

    $res = new Response();

    $this->headers = $headers;
    $this->request = $req;
    $this->response = call_user_func_array($this->app, array($req, $res));
}

例如:

public function testGetProducts()
{
    $this->dispatch('/products');

    $this->assertEquals(200, $this->response->getStatusCode());
}

但是,尽管响应中包含状态代码和标头之类的内容,(string) $response->getBody() 是空的,所以我无法检查 HTML 中是否存在元素。当我在浏览器中运行相同的路由时,我得到了预期的 HTML 输出。另外,如果我echo $response->getBody(); exit; 然后在浏览器中查看输出,我会看到 HTML 正文。有什么理由,在我的实施中,我在我的测试中没有看到这一点? (在 CLI 中,我猜是不同的环境)

【问题讨论】:

    标签: php slim


    【解决方案1】:

    $response->getBody() 将是空的,因为您已经设置了解析的主体。将它作为字符串放入RequestBody 更容易,就像它通过电线进入时一样。

    比如这样的:

    protected function dispatch($path, $method='GET', $data=array())
    {
        // Prepare a mock environment
        $env = Environment::mock(array(
            'REQUEST_URI' => $path,
            'REQUEST_METHOD' => $method,
            'CONTENT_TYPE' => 'application/json',
        ));
    
        // Prepare request and response objects
        $uri = Uri::createFromEnvironment($env);
        $headers = Headers::createFromEnvironment($env);
        $cookies = [];
        $serverParams = $env->all();
        $body = new RequestBody();
        if (!empty($data)) {
            $body->write(json_encode($data));
        }
    
        // create request, and set params
        $req = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
        $res = new Response();
    
        $this->headers = $headers;
        $this->request = $req;
        $this->response = call_user_func_array($this->app, array($req, $res));
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多