更新时间:2023-02-19 17:29:34
使用Laravel 5.2,我正在通过将带有输入的请求和带有断言的闭包传递给中间件来对中间件进行单元测试.
Using Laravel 5.2, I am unit testing my middleware by passing it a request with input and a closure with assertions.
所以我有一个中间件 class GetCommandFromSlack
,它将Post中 text
字段的第一个单词(来自Slack斜杠命令的文本)解析为一个新字段,称为 command
,然后将 text
字段修改为不再包含第一个单词.它有一个具有以下签名的方法:public function handle(\Illuminate\Http\Request $request, Closure $next)
.
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.