4

I created a feature test api.

CategoryApiTest.php

namespace Tests\Feature;

use App\Models\Category;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\JsonResponse;
use Tests\TestCase;

class CategoryApiTest extends TestCase
{
    use RefreshDatabase;

    protected $faker;

    public function setUp(): void
    {
        parent::setUp(); // TODO: Change the autogenerated stub

        $this->user = $this->faker = Category::factory()
            ->create([
                'name' => 'Food',
                'description' => 'This is the food category',
                'menu' => true,
                'image' => 'IMG_4985',
                'parent_id' => '1'
            ]);
    }

    ...

    public function testUpdateCategory()
    {
        $response = $this->putJson('/api/categories/1', [
            'name' => 'Water Update',
            'description' => 'This is the water category update',
            'menu' => true,
            'image' => 'IMG_56898',
            'parent_id' => '1'
        ]);

        $response->assertStatus(JsonResponse::HTTP_OK)
            ->assertJsonFragment([
                'name' => 'Water Update',
                'slug' => 'water-update',
                'parent_id' => 1
            ]);
    }

    ...
}

This case always return fail, because cannot find category with id = 1.
I checked list categories and I see:
enter image description here

I create file .env.testing and database_test but I think phpunit.xml doesn't use file .env.testing so RefreshDatabase not working.

Data test does not refresh. Something wrong, please help me fix it.

Kmeixner
  • 1,664
  • 4
  • 22
  • 32
Huan Ho
  • 145
  • 2
  • 9
  • Get the ID from what was created by your factory. Don't assume that auto-incrementing columns will always start at 1 when you first create a table since the next auto-increment value will not always be predictable (depending on the underlying DBMS) – apokryfos Oct 27 '20 at 09:23
  • 1
    If you are not using a sqlite database the `RefreshDatabase` trait will only migrate the database once and afterwards use transactions to reset the database, so you cannot assume that the id will be 1, you can see it [here](https://github.com/laravel/framework/blob/8.x/src/Illuminate/Foundation/Testing/RefreshDatabase.php#L62). As apokryfos pointed out you should not hardcode some ids in your test, use the category that your factory created for you. – Remul Oct 27 '20 at 09:26
  • So, It mean Should I remove `use RefreshDatabase `? – Huan Ho Oct 27 '20 at 09:30
  • No you should write a proper test that does not care what id the category has, you want to test category updates, which id the category has is irrelevant. – Remul Oct 27 '20 at 09:34
  • If the only reason you used `RefreshDatabase` is to enforce the id to start at 1 for every time the test runs, then yes, remove `RefreshDatabase` as it's not what its purpose is. – apokryfos Oct 27 '20 at 09:59

0 Answers0