加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用PHPUnit测试Slim 3路由时,$response-> getBody()为空

发布时间:2020-12-13 16:00:17 所属栏目:PHP教程 来源:网络整理
导读:我使用以下方法在我的 PHPUnit测试中调度Slim应用程序的路径: protected function dispatch($path,$method='GET',$data=array()){ // Prepare a mock environment $env = Environment::mock(array( 'REQUEST_URI' = $path,'REQUEST_METHOD' = $method,)); /
我使用以下方法在我的 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());
}

但是,响应中的状态代码和标题之类的内容,(字符串)$response-> getBody()为空,因此我无法检查HTML中是否存在元素.当我在浏览器中运行相同的路径时,我得到了预期的HTML输出.另外,如果我回显$response-> getBody();出口;然后在浏览器中查看输出,我看到HTML正文.有没有理由,我的实施,我在测试中没有看到这个? (在CLI中,我猜不同的环境)

解决方法

当您设置已解析的正文时,$response-> getBody()将为空.将它作为字符串放入RequestBody更容易,就像它通过线路进入时设置的方式一样.

即是这样的:

protected function dispatch($path,'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,$body);
    $res = new Response();

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读