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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With