我安装了 Symfony 4,然后安装了 API 平台。
然后我创建这样的测试类
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' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592d3c2a2d193c21383429353c773a3634" rel="noreferrer noopener nofollow">[email protected]</a>',
'password' => 'jamielann1',
],
]);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
当我运行./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
我的问题是,为什么它没有作为 application/json 接收?正确的做法是什么?
最佳答案
来自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"}'
);
关于php - 如何在 WebTestCase 上进行 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57884508/