dqf2015 2015-10-23 07:44
浏览 57
已采纳

测试是否从AJAX请求或从PhpUnit调用方法

I've started implementing unit tests on my current project.

While all unit test currently pass, due to convenience, I made a change to the jsonResponse method to also send json headers. This helps me see the json response as a tree in the Chrome console.

Now the unit tests are failing due to

Cannot modify header information - headers already sent by
(output started at [fullPath]/phpunit/src/Util/Printer.php:134)

Digging deeper, I found that this can be fixed by adding @runInSeparateProcess in the docBlocks.

But this just leads to:

PHP Fatal error: Class 'PHPUnit_Util_Configuration' not found in - on line 365
PHP Stack trace:
PHP 1. {main}() -:0

This is one of my json methods (this is called at the end of several methods which are called through AJAX requests):

/**
 * Helper function to print a json encoded success message back to the frontend.
 *
 * @param array $returnData
 *
 * @return bool
 *
 * @runInSeparateProcess
 */
public function returnJsonSuccess($returnData = [])
{
    header('Content-Type: application/json');
    echo json_encode(
        [
            "success" => true,
            "data"    => $returnData,
        ]
    );
    return true;
}

So, cutting to the chase, how can i make this work properly?

One of my options is to detect if the method is called from a unit test and conditionally send the headers only if it's called normally. I'm thinking easiest way is to define an environment variable or a constant in the bootstrap file and check for that in my BaseController.

Is there a cleaner way of getting my unit tests to work again while also keeping the json headers sent?

  • 写回答

2条回答 默认 最新

  • doupin8555 2015-10-23 08:08
    关注

    Solved it myself with:

    /**
     * Helper function to print a json encoded success message back to extJs.
     *
     * @param array $returnData
     *
     * @return bool
     */
    public function returnJsonSuccess($returnData = [])
    {
        $request = $this->getRequest();
        if ($request && $request->isXmlHttpRequest()) {
            header('Content-Type: application/json');
        }
        echo json_encode(
            [
                "success" => true,
                "data"    => $returnData,
            ]
        );
        return true;
    }
    

    ZendFramework, using the Request class, can detect if the call is made from an AJAX request or not. This way, I only send the headers if there's an AJAX request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址