Unit test Laravel middleware

Nealv picture Nealv · Jul 14, 2015 · Viewed 8.4k times · Source

I am trying to write unit tests for my middleware in Laravel. Does anyone know a tutorial, or have an example of this ?

I have been writing a lot of code, but there must be a better way to test the handle method.

Answer

perkee picture perkee · Apr 11, 2016

Using Laravel 5.2, I am unit testing my middleware by passing it a request with input and a closure with assertions.

So I have a middleware class GetCommandFromSlack that parses the first word of the text field in my Post (the text from a Slack slash command) into a new field called command, then modifies the text field to not have that first word any more. It has one method with the following signature: public function handle(\Illuminate\Http\Request $request, Closure $next).

My Test case then looks like this:

use App\Http\Middleware\GetCommandFromSlack;
use Illuminate\Http\Request;

class CommandsFromSlackTest extends TestCase
{
  public function testShouldKnowLiftCommand()
  {
    $request = new Illuminate\Http\Request();
    $request->replace([
        'text' => 'lift foo bar baz',
    ]);
    $mw = new \App\Http\Middleware\GetCommandFromSlack;
    $mw->handle($request,function($r) use ($after){
      $this->assertEquals('lift',       $r->input('command'));
      $this->assertEquals('foo bar baz',$r->input('text'));
    });
  }
}

I hope that helps! I'll try to update this if I get more complicated middleware working.