douou1891 2014-12-22 12:52
浏览 31

Yii2期望JSON POST的API端点的代码测试

Does anyone have any experience of using Codeception tests within Yii2 to test an API endpoint that expects a JSON request?

Right now, I'm just hoping to do a basic check for a 200 response code and a JSON body.

Currently, my test breaks with "[PHPUnit_Framework_ExceptionWrapper] Bad request."

Edit
It turns out this 'Bad request' error is thrown by my own code, because the $request->getRawBody() is empty. That is, the parameters that I have set in the call to sendPOST() are not making it through into the Yii request object. Without them present, the request is doomed to fail.
/Edit

Edit2
Remove headers from the test (as per comments) and it works.
/Edit2

I'm trying to use the sendPOST() method of the Codeception REST module.

I'm not confident that Codeception\Lib\Connector\Yii2.php is correctly mapping my parameter data from the BrowserKit Request to the corresponding Yii Request. That is, the request that goes into doRequest() has my data, but $app->getRequest() later in that same function lacks it.

Here's my test:

$I = new FunctionalTester($scenario);
$I->haveHttpHeader('Content-Type', 'application/json'); //remove
$I->haveHttpHeader('Accept', 'application/json'); //remove
$I->sendPost(
    '/index-test.php/api/v1/poi/bbox',
    [
        'bbox' => [
            'minLat' => 51.53667954545721,
            'minLng' => -0.14273375272750854,
            'maxLat' => 51.53749870786214,
            'maxLng' => -0.13856828212738037
        ]
    ]
);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();

And here's a CURL representation of a working request:

curl \
--request POST \
--header "Accept: application/json" \
--header "Content-Type: application/json; charset=UTF-8" \
--data '{ "bbox": {"minLng": -0.152573, "minLat": 51.529012, "maxLng": -0.124691, "maxLat": 51.54104} }' \
<endpoint>

Did I do something wrong at an earlier stage? Or, am I approaching this the wrong way? Perhaps there's a better way to send a JSON POST request like this?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!
    • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?