php - 如何在 WebTestCase 上进行 JSON 请求

标签 php symfony phpunit api-platform.com symfony-4.3

我安装了 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/

相关文章:

java - 如何将 .pdf 转换为 .png

php - PHP 中使用 self::的单元测试类

php - Laravel Sail 没有在我的 macbook m1 上运行

PHP/MySQL 查询/循环

php - 使用 PHP 合并图像时的图像透明度和 alpha

交响乐2.1。如何从一个实体获取数据并将其显示在每一页上?

php - 提交表单时Symfony 2表单错误 "This form should not contain extra fields."

php - 修改 Sonata Media Bundle 时预览列消失

PHPUnit - 测试上次插入 ID

PHPUnit:期望以数组作为参数的方法调用