Reputation: 1991
I install Symfony 4 and then 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' => '[email protected]',
'password' => 'jamielann1',
],
]);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
When I run ./bin/phpunit
, I got error message
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? What is the proper way?
Upvotes: 2
Views: 4148
Reputation: 1637
From 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"}'
);
Upvotes: 2
Reputation: 8374
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
$response = $this->client->request('POST', $this->host . '/api/users.json', [
'json' => [
'username' => 'jamielann1',
'email' => '[email protected]',
'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:
'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 ...
Upvotes: 0