A
A
Alexander Lysenko2018-08-05 19:14:53
PHP
Alexander Lysenko, 2018-08-05 19:14:53

How to test api correctly?

There is an api for posts. Implemented resource controller (CRUD)
How to properly test this controller?
Well, for example, in my index method

$data = Post::all();
return PostResource::collection($data);

route to it test.com/api/post
How to test this link?
I just don’t fully understand whether it is necessary to bind the base here or not, or to make a test base?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Mitrahovich, 2018-08-05
@LysenkoSasha

In this case, I usually use a test sqlite in memory database, adding to phpunit.xml:

<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>

After that, in the test, always reset and roll data into the database at each start: Next, using the factories, we create records in the test database. As an example:
$task = factory(\App\Task::class)->create([
     'archive' => false
]);

We send a request to our URL (you will have it /api/post). Again, for example: And as a result, we check the necessary data, for example, that the response from the server came with status 200 and that the result should be a response in JSON format and exactly the data that we previously placed in the test database:
$response->assertStatus(200)
          ->assertJson([$task->toArray()]);

See more about all assertions here: https://laravel.com/docs/5.6/http-tests

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question