phplaravelunit-testinglaravel-unit-test

How to pass an object as parameter in unit test? (laravel)


I have a data object below that I tried to test using postman. I just don't know how to make this possible also in laravel's unit testing. I have visited this link but it doesn't helped in my case.

{
    "user_id": 1,
    "name": "juan",
    "address": [
        "state": "Auckland",
        "country": "New Zealand",
    ],
    "school": [
        {
            "school_name": "Kristin School",
            "year": 2016
        },
        {
            "school_name": "ACG Parnell College",
            "year": 2018
        },
    ],
    // and more...
}

How can we pass such an object above in unit testing? Is there any way to achieve this?

$response = $this->post('/logbooks/user', ['Authorization': 'Bearer' + $token]);

Solution

  • As you can find in the Laravel docs for HTTP tests, you can send a php array as follows:

    $payload = [
        "user_id" => 1,
        "name" => "juan",
        "address" => [
            "state" => "Auckland",
            "country" => "New Zealand",
        ],
    ];
    
    
    $response = $this->postJson(
        '/logbooks/user', $payload, ['Authorization': 'Bearer' + $token]
    );
    

    It takes your php $payload array and encodes it as JSON and sends it. If you have an object you can cast it with $myArray = (array) $myObject.