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

时间:2014-03-19 16:12:31

标签: php json symfony testing

我在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());

我如何检查?

1 个答案:

答案 0 :(得分:11)

我自己回答。通过Google搜索我找到了JsonResponse tests,我发现了如何对其进行测试,因此我将代码转换为:

$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());

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