How to test laravel controller method?

Member

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

How to test laravel controller method?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 10 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.

Related Threads:

How to test patch method in laravel?
How test unauthorized method in laravel?
How to write a test for method in laravel using phpspec?
How to unit test a controller in laravel?
How to invoke a controller method from koa router?
How to test parent call method in a class for phpspec?