php – Symfony2:检查JSON值是否响应以及测试中是否为TRUE

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – Symfony2:检查JSON值是否响应以及测试中是否为TRUE脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Symfony2书中读过 Testing,但没有找到任何有用的,所以,我正在我的应用程序中为控制器创建测试,这是我试图测试的控制器(只是相关代码):
public function createCompanyAction(Request $request) {
    $response = array();
    $response["success"] = false;

    try {
    if (statement) {
            // do the magic here
            $response["success"] = true;
        } else {
            $response['errors'] = "some error";
        }
    } catch (Exception $ex) {
        $response["exception"] = $ex->getMessage();
    }

    return new JsonResponse($response);
}

只有当$response在成功密钥中具有TRUE值时,测试才会通过,但我不知道如何从我的测试控制器中检查它.这是我的代码

$client->request('POST','/create-company',$data);
$response = $client->getResponse();

$this->assertEquals(200,$client->getResponse()->getStatusCode(),'HTTP code is not 200');
$this->assertTrue($response->headers->contains('Content-tyPE','application/json'),'Invalid JSON response');

$this->assertNotEmpty($client->getResponse()->getContent());

我怎么检查这个?

我回答自己.搜索谷歌找到了JsonResponse tests,我发现了如何测试它,所以我将我的代码转换为:
$client->request('POST',$data);

$response = $client->getResponse();
// test if response is OK
$this->assertSame(200,$client->getResponse()->getStatusCode());
// Test if Content-Type is valid application/json
$this->assertSame('application/json',$response->headers->get('Content-Type'));
// Test if company was inserted
$this->assertEquals('{"success":"true"}',$response->getContent());
// Test that response is not empty
$this->assertNotEmpty($client->getResponse()->getContent());

我还没有测试但它可能有用.

脚本宝典总结

以上是脚本宝典为你收集整理的php – Symfony2:检查JSON值是否响应以及测试中是否为TRUE全部内容,希望文章能够帮你解决php – Symfony2:检查JSON值是否响应以及测试中是否为TRUE所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。