laravelapiresttestingphpunit

Laravel 9 error running PHP Unit tests fails with error json not found


I have created the following unit test:

<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

class DistrictKindTest extends TestCase
{
    /**
     * Index method unit test.
     *
     * @return void
     */
    public function test_index()
    {
        $response = $this->json('GET', '/api/distinct-kinds');
        $response->assertStatus(200);
    }
}

Then I run command: vendor/bin/phpunit --coverage-html tests/coverage I got the following errors:

PHPUnit 9.6.3 by Sebastian Bergmann and contributors.

E....                                                               5 / 5 (100%)

Time: 00:00.151, Memory: 20.00 MB

There was 1 error:

1) Tests\Unit\DistrictKindTest::test_index
Error: Call to undefined method Tests\Unit\DistrictKindTest::json()

/var/www/html/tests/Unit/DistrictKindTest.php:23

ERRORS!
Tests: 5, Assertions: 13, Errors: 1.

What should I use to fix this error? Maybe I have to add use of some class to fix this error? Could you advice me on how to fix it?


Solution

  • This type of testing is Release testing. Unit tests are for testing specific classes, not accessing complete routines.

    Try using the TestCase used by Release tests:

    use Tests\TestCase;