Symfony 网络测试用例 JSON
Symfony web test case JSON
我怎样才能 运行 网络测试用例再次 API?关于功能测试的默认指南只给出以下命令:
$client = static::createClient();
$crawler = $client->request('GET', '/some-url');
爬虫 class 是一个 DOM 爬虫。我检查了 FrameworkBundle\Client class 的参考,但找不到允许我发出 returns 原始响应请求的方法。至少这样,我将能够 json_decode 输出并进行测试。
我可以用什么来实现这个?
调用$client->request(...)
后,可以$client->getResponse()
获取服务器响应。
然后您可以断言状态代码并检查其内容,例如:
$client->request('GET', '/my-url');
$response = $client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$responseData = json_decode($response->getContent(), true);
// etc...
willdurand/rest-extra-bundle bundle provides additional helpers to test JSON。为了测试相等性,已经有一个用于此目的的内置断言:
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);
请注意,assertJsonStringEqualsJsonString
断言将负责 $expectedJson
和 $response
字符串的规范化。
有一个 PHPUnit\Framework\Assert::assertJson() 方法,因为 this commit
您还可以测试 'Content-Type' 的响应。
$response = $client->getResponse();
$this->assertTrue($response->headers->contains('Content-Type', 'application/json'));
$this->assertJson($response->getContent());
$responseData = json_decode($response->getContent(), true);
我怎样才能 运行 网络测试用例再次 API?关于功能测试的默认指南只给出以下命令:
$client = static::createClient();
$crawler = $client->request('GET', '/some-url');
爬虫 class 是一个 DOM 爬虫。我检查了 FrameworkBundle\Client class 的参考,但找不到允许我发出 returns 原始响应请求的方法。至少这样,我将能够 json_decode 输出并进行测试。
我可以用什么来实现这个?
调用$client->request(...)
后,可以$client->getResponse()
获取服务器响应。
然后您可以断言状态代码并检查其内容,例如:
$client->request('GET', '/my-url');
$response = $client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$responseData = json_decode($response->getContent(), true);
// etc...
willdurand/rest-extra-bundle bundle provides additional helpers to test JSON。为了测试相等性,已经有一个用于此目的的内置断言:
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);
请注意,assertJsonStringEqualsJsonString
断言将负责 $expectedJson
和 $response
字符串的规范化。
有一个 PHPUnit\Framework\Assert::assertJson() 方法,因为 this commit 您还可以测试 'Content-Type' 的响应。
$response = $client->getResponse();
$this->assertTrue($response->headers->contains('Content-Type', 'application/json'));
$this->assertJson($response->getContent());
$responseData = json_decode($response->getContent(), true);