"试图获得非对象的属性"在Symfony 4.1上执行JSON请求测试时

时间:2018-06-12 09:48:55

标签: json object testing phpunit symfony4

我试图编写一个测试用例来测试我的操作,使用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工作。但测试会告诉我

  

试图获得财产' createdAt'非对象

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

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发送到控制器以进行测试的方法。那么,它为什么会失败?

1 个答案:

答案 0 :(得分:1)

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

$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
}