Search code examples
phpsymfonygetphpunit

Error: Call to undefined method get() in PHPUnit Symfony


I am trying to execute my first unit test with PHPUnit 9.0.0 and Symfony 5.1.8. This test must to pass if the HTTP response is 200.

<?php declare(strict_types=1);

namespace Tests\Infrastructure\Api\Controller;

use PHPUnit\Framework\TestCase;

class ControllerTests extends TestCase
{
    /** @test */
     public function route(): void
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    
    }

}

I obtain the error:

There was 1 error:

  1. Tests\Infrastructure\Api\Controller\SupplierControllerTests::route Error: Call to undefined method Tests\Infrastructure\Api\Controller\SupplierControllerTests::get()

I thought the Get method was a default method, imported by PHPUnit\Framework\TestCase, but it do not look that.

Have I to add a Get method into my class ControllerTests? How can i develop it to test the HTTP response?

Thanks in advance


Solution

  • You need to extend the WebTestCase provided by Symfony, not the default TestCase provided by PHPUnit.

    Here is an example for a similar test you are trying to write:

    namespace App\Tests\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
    
    class PostControllerTest extends WebTestCase
    {
        public function testShowPost()
        {
            $client = static::createClient();
    
            $client->request('GET', '/post/hello-world');
    
            $this->assertEquals(200, $client->getResponse()->getStatusCode());
        }
    }