[英]How to do JSON request on WebTestCase
I install Symfony 4 and then API Platform.我先安装 Symfony 4,然后再安装 API Platform。
Then I create Test class like this然后我像这样创建测试类
class UserFunctionalTest extends WebTestCase
{
/** @var string */
protected $host = "https://wikaunting-api.local";
/** @var KernelBrowser */
protected $client;
protected function setUp()
{
$this->client = static::createClient();
}
public function testCreateUser()
{
$response = $this->client->request('POST', $this->host . '/api/users.json', [
'json' => [
'username' => 'jamielann1',
'email' => 'test@example.com',
'password' => 'jamielann1',
],
]);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
When I run ./bin/phpunit
, I got error message当我运行
./bin/phpunit
,我收到错误消息
Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException: "The content-type "application/x-www-form-urlencoded" is not supported. Supported MIME types are "application/ld+json", "application/json", "text/html"." at /home/vagrant/Code/testcode/vendor/api-platform/core/src/EventListener/DeserializeListener.php line 130
My question is, why it is not received as application/json?我的问题是,为什么它不是作为 application/json 接收的? What is the proper way?
什么是正确的方法?
you can set the Content-Type
header and set it to one of the json types (see your error message), the key to put the headers in, is headers
您可以设置
Content-Type
标头并将其设置为 json 类型之一(请参阅您的错误消息),将标头放入的关键是headers
$response = $this->client->request('POST', $this->host . '/api/users.json', [
'json' => [
'username' => 'jamielann1',
'email' => 'test@example.com',
'password' => 'jamielann1',
],
'headers' => [
'Content-Type' => 'application/json',
// or just 'Content-Type: application/json', without the key
],
]);
sadly the Symfony\\Contracts\\HttpClient\\HttpClientInterface
says something to the json
parameter:遗憾的是
Symfony\\Contracts\\HttpClient\\HttpClientInterface
对json
参数说了些什么:
'json' => null, // array|\JsonSerializable - when set, implementations MUST set the "body" option to
// the JSON-encoded value and set the "content-type" headers to a JSON-compatible
// value if they are not defined - typically "application/json"
which apparently doesn't work as expected ...这显然没有按预期工作......
From https://symfony.com/doc/current/testing.html#working-with-the-test-client来自https://symfony.com/doc/current/testing.html#working-with-the-test-client
// submits a raw JSON string in the request body
$client->request(
'POST',
'/submit',
[],
[],
['CONTENT_TYPE' => 'application/json'],
'{"name":"Fabien"}'
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.