Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Check if JSON value is in response and if it's TRUE in test

I have read Testing in Symfony2 book but did not find any useful to do this so, I'm creating test for controllers in my application and this is the controller (just relevant code) I'm trying to test:

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);
} 

The test will pass only if $response has TRUE value in success key but I don't know how to check that from my test controller. This is the code I have:

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

How I check this?

like image 659
ReynierPM Avatar asked Mar 19 '14 16:03

ReynierPM


1 Answers

I answer myself. Searching trough Google I found JsonResponse tests and I found how to test it, so I transform my code into this:

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

I have not tested yet but it may works.

like image 179
ReynierPM Avatar answered Sep 30 '22 01:09

ReynierPM