21

How can I run a webtestcase agains an API? The default guide regarding functional tests only give the following command:

$client = static::createClient(); $crawler = $client->request('GET', '/some-url'); 

The Crawler class is a DOM crawler. I checked the reference for the FrameworkBundle\Client class and I couldn't find a method that will allow me to make a request that returns raw Response. At least that way, I will be able to json_decode the output and do my tests.

What can I use to achieve this?

3 Answers 3

34

After you do $client->request(...) call, you can do $client->getResponse() to get server response.

You can then assert status code and check it's contents, for example:

$client->request('GET', '/my-url'); $response = $client->getResponse(); $this->assertSame(200, $response->getStatusCode()); $responseData = json_decode($response->getContent(), true); // etc... 
Sign up to request clarification or add additional context in comments.

Comments

11

There is a PHPUnit\Framework\Assert::assertJson() method since this commit You can also test for a Content-Type response header.

$response = $client->getResponse(); $this->assertTrue($response->headers->contains('Content-Type', 'application/json')); $this->assertJson($response->getContent()); $responseData = json_decode($response->getContent(), true); 

Comments

5

The willdurand/rest-extra-bundle bundle provides additional helpers to test JSON. To test equality there is already a built-in assertion for this purpose:

use Bazinga\Bundle\RestExtraBundle\Test\WebTestCase as BazingaWebTestCase; // ... $client->request('GET', '/my-url'); $response = $client->getResponse(); $this->assertJsonResponse($response, Response::HTTP_OK); $this->assertJsonStringEqualsJsonString($expectedJson, $response); 

Note that the assertJsonStringEqualsJsonString assertion will take in charge the normalization of both $expectedJson and $response strings.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.