Mister Verleg
Mister Verleg

Reputation: 4303

Laravel (5.8) php unit make raw post request

To make a regular test post request one can use:

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

However, the json() method expects an array as the data parameter. however my data needs to be a raw string:

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

Is there a method I can use to send a post request with the raw data?

Upvotes: 2

Views: 1600

Answers (2)

Oliver Kurmis
Oliver Kurmis

Reputation: 58

Just use call() :

$this->call('POST', '/your/route',  [], [], [], [], 'your request body');

Upvotes: 0

Gerard Roche
Gerard Roche

Reputation: 6411

You can decode your string and pass it as an array.

$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)
]);

If this is a common operation in your test suite then create a helper method in a base application test case:

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

Or a trait would be better, something you can use only when needed, e.g:

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

Alternate naming convention: jsonFromString().

Upvotes: 2

Related Questions