How do I make route model binding work in Laravel during unit tests?

Viewed 1023

Most of my unit tests use WithoutMiddleware so I can test the controller and the resource endpoint. However route model binding is a middleware, so the controllers aren't getting the models they need.

1 Answers

This was my question, and it may not be relevant anymore. It used to be that laravel tests could use middleware or not use middleware. So the route-model-binding would be on or off along with everything else. Now Laravel tests support the omission of specific middle-wares. So you can use something like this... and keep other middleware on including the binding stuff.

namespace Tests\Feature;
use App\Http\Middleware\VerifyCsrfToken;
use ...
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;

class BankDisplayControllerTest extends TestCase{

    use DatabaseTransactions;

    //use WithoutMiddleware;

    protected function setUp(){
        parent::setUp();

        $this->withoutMiddleware([VerifyCsrfToken::class]);
    }
   ...
Related