【问题标题】:Symfony2: Check if JSON value is in response and if it's TRUE in testSymfony2:检查 JSON 值是否在响应中以及在测试中是否为 TRUE
【发布时间】:2014-03-19 16:12:30
【问题描述】:

我已经阅读了 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);
} 

只有当$responsesuccess 键中有 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());

我如何检查这个?

【问题讨论】:

    标签: php json symfony testing


    【解决方案1】:

    我自己回答。通过谷歌搜索我找到了JsonResponsetests,我找到了如何测试它,所以我将我的代码转换成这样:

    $client->request('POST', '/create-company', $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());
    

    我还没有测试,但它可能有效。

    【讨论】:

    • 最好不要硬编码 HTTP 状态代码。随着时间的推移,它使代码的可读性和可维护性降低。我建议为此使用常量\Symfony\Component\HttpFoundation\Response::HTTP_OK
    • 或者您可以使用$this->assertTrue($client->getResponse()->isSuccessful()); 代替常量,随心所欲:)
    猜你喜欢
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    相关资源
    最近更新 更多