1

我安装 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' => 'test@example.com',
                '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

我的问题是,为什么它没有作为应用程序/json 接收?什么是正确的方法?

4

2 回答 2

1

来自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"}'
);
于 2021-01-14T09:20:48.227 回答
0

您可以设置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
        ],
    ]);

可悲的是,参数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"

这显然没有按预期工作......

于 2019-09-11T08:50:02.820 回答