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

1.1k views Asked by At

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

There are 2 answers

1
codedge On BEST ANSWER

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.

2
Eden Moshe On

First to know that such tests are not a "unit test" type. Note that the code will run and you should be alert to changes that running the code may entail (updating data in the database, contacting external providers).

Of course, all of this can be mocked, and it is recommended that you read about it carefully.

class FooTest extends TestCase {
 public function testBar()
 {
   $response = $this->post('/api/v1/yourapi', 
           [
            "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 
               ] 
         ] 
]);
    $response->assertStatus(200);
    $response->assertJsonStructure([...]);

    $response->assert....();
 }
}

As I wrote in the comment below, the JSON you attached was invalid. You treated the array as an object, adding unnecessary commas.

It is recommended to use an array that the IDE knows to recognize