How to test laravel controller method?

Member

by darion , in category: Third Party Scripts , 4 months ago

How to test laravel controller method?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 4 months ago

@darion 

To test a Laravel controller method, you can use PHPUnit to write unit tests. Here is an example of how you can test a controller method in Laravel:

  1. Create a new test class that extends the Laravel TestCase class. This class will contain the test methods for the controller method you want to test.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use IlluminateFoundationTestingRefreshDatabase;
use TestsTestCase;

class ExampleControllerTest extends TestCase
{
    use RefreshDatabase;

    public function testControllerMethod()
    {
       // Test logic here
    }
}


  1. Within the testControllerMethod() method, you can make a request to the controller method using the $this->get(), $this->post(), $this->put(), or $this->delete() methods provided by Laravel's testing framework.
1
2
3
4
5
6
public function testControllerMethod()
{
    $response = $this->get('/example-route');

    $response->assertStatus(200);
}


  1. You can also assert that the response contains certain data, such as a specific value in the JSON response or a piece of HTML content.
1
2
3
4
5
6
7
8
9
public function testControllerMethod()
{
    $response = $this->get('/example-route');

    $response->assertStatus(200)
             ->assertJson([
                 'key' => 'value'
             ]);
}


  1. Run the test using PHPUnit by running the following command in your terminal:
1
phpunit --filter testControllerMethod


This will run the specific test method and output the results in your terminal. Make sure to replace "testControllerMethod" with the actual name of your test method.