Reputation:
I'm trying to write a test case to test my operation to persist data into the database using Symfony 4.1. The operation is already working and it is the following:
public function storeAction(Request $request)
{
$data = json_decode($request->getContent());
try {
$entityManager = $this->getDoctrine()->getManager();
$createdAt = \DateTime::createFromFormat("Y-m-d H:i:s", $data->createdAt);
$concludedAt = \DateTime::createFromFormat("Y-m-d H:i:s", $data->concludedAt);
$task = new Task();
$task->setDescription($data->description);
$task->setCreatedAt($createdAt);
$task->setConcludedAt($concludedAt);
$entityManager->persist($task);
$entityManager->flush();
return $this->json([
"message" => "Task created",
"status" => 200
]);
} catch (\Exception $e) {
return $this->json([
"error" => [
"code" => 500,
"message" => $e->getMessage(),
"file" => $e->getFile()
]
]);
}
}
Using Insonmnia REST with it sending a JSON works. But the test will show me
Trying to get property 'createdAt' of non-object
pointing to my controller class. This is the test:
public function testStoreTaskEndpointStatusCode200AndTaskCreated()
{
$client = static::createClient();
$client->request(
"POST",
"/tasks",
[],
[],
[
"CONTENT_TYPE" => "application/json",
'{"description": "Goodbye, world!", "createdAt": "2012-12-21 00:00:00", "concludedAt": "2012-12-21 00:00:01"}'
]
);
$obj = json_decode($client->getResponse()->getContent());
var_dump($obj); // <~ the error message is shown
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$this->assertTrue($client->getResponse()->headers->contains("Content-Type", "application/json"));
}
The documentation shows this way to send JSON to the controller for testing purposes. So, why does it fail?
Upvotes: 1
Views: 77
Reputation: 39430
You should pass the content data as seven argument of the request method as example:
$client->request(
"POST",
"/tasks",
[],
[],
[
"CONTENT_TYPE" => "application/json",
],
'{"description": "Goodbye, world!", "createdAt": "2012-12-21 00:00:00", "concludedAt": "2012-12-21 00:00:01"}'
);
PS: I suggest you to check if the json_encode find errors by checking
$obj = json_decode($client->getResponse()->getContent());
if (false === $obj) {
// Invalid json provided
}
Upvotes: 0