"Trying to get property of non-object" 在 Symfony 4.1 上执行 JSON 请求测试时

"Trying to get property of non-object" when executing test of a JSON request on Symfony 4.1

我正在尝试编写一个测试用例来测试我使用 Symfony 4.1 将数据持久保存到数据库中的操作。该操作已在运行,如下所示:

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()
            ]
        ]);
    }
}

使用 Insonmnia REST 发送 JSON 作品。但是测试会告诉我

Trying to get property 'createdAt' of non-object

指向我的控制器class。这是测试:

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"));
}

文档显示了这种发送 JSON 到控制器以进行测试的方式。那么,为什么会失败?

您应该将内容数据作为请求方法的七个参数传递,例如:

$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: 我建议你通过检查

来检查json_encode是否发现错误
$obj = json_decode($client->getResponse()->getContent());

if (false === $obj) {
   // Invalid json provided
}