【问题标题】:Laravel (5.8) php unit make raw post requestLaravel (5.8) php 单元发出原始的 post 请求
【发布时间】:2020-01-13 07:31:50
【问题描述】:

要进行常规测试发布请求,可以使用:

   // signature: json(string method,string url, array data)
   $response = $this->json("post","/api/oee/v1/statuses/log", ["data" =>$data])

但是,json() 方法需要一个数组作为数据参数。 但是我的数据需要是原始字符串:

{ "data": [ { "component_id": 16, "value": 265, "time": 1556520087 }, { "component_id": 16, "value": 324, "time": 1556520087 }, { "component_id": 16, "value": 65, "time": 1556520087 } ] }

我可以使用一种方法来发送包含原始数据的发布请求吗?

【问题讨论】:

  • 也许你可以只使用json_decode($data, true) $data 字符串。然后将其传递给json 方法。

标签: php laravel phpunit


【解决方案1】:

您可以解码您的字符串并将其作为数组传递。

$data = '{ "data": [ { "component_id": 16, "value": 265, "time": 1556520087 }, { "component_id": 16, "value": 324, "time": 1556520087 }, { "component_id": 16, "value": 65, "time": 1556520087 } ] }';

$response = $this->json("post","/api/oee/v1/statuses/log", [
    "data" => json_decode($data, true)
]);

如果这是您的测试套件中的常见操作,则在基本应用程序测试用例中创建一个辅助方法:

public function jsonString($method, $uri, $data, array $headers = [])
{
    return $this->json($method, $uri, json_decode($data, true), $headers);
}

或者一个特质会更好,只有在需要时才能使用,例如:

trait MakesRawJsonRequests
{
    public function jsonRaw($method, $uri, $data, array $headers = [])
    {
        return $this->json($method, $uri, json_decode($data, true), $headers);
    }
}

备用命名约定:jsonFromString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多