代码之家  ›  专栏  ›  技术社区  ›  fermoga

在symfony 4.1上执行json请求测试时“尝试获取非对象的属性”

  •  1
  • fermoga  · 技术社区  · 6 年前

    我正在尝试编写一个测试用例来测试使用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()
                ]
            ]);
        }
    }
    

    使用insonnia 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 回复  |  直到 6 年前
        1
  •  1
  •   Matteo    6 年前

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

    $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编码是否发现错误

    $obj = json_decode($client->getResponse()->getContent());
    
    if (false === $obj) {
       // Invalid json provided
    }