【问题标题】:How to test a middleware with phpunit in laravel 5.5?如何在 laravel 5.5 中使用 phpunit 测试中间件?
【发布时间】:2018-09-05 16:46:09
【问题描述】:

如何测试我的中间件? 在这里,我正在测试管理员是否可以访问受中间件保护的路由,如果用户没有特权 ip,则返回 500 - 然后中间件在尝试访问 /500 页面时返回 401(未授权)。

我的测试:

use App\Http\Middleware\OnlyAdminIp;
use Illuminate\Http\Request;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class HttpTests extends TestCase
{
    use DatabaseTransactions;

   /** @test */
    public function if_a_500_page_returns_a_500_response_for_admin()
    {
        $request = Request::create(config('app.url') . '500', 'GET');
        $middleware = new OnlyAdminIp();
        $response = $middleware->handle($request, function () {});
        $this->assertEquals($response->getStatusCode(), 401);
    }
}

我的中间件:

namespace App\Http\Middleware;

use App\IpList;
use Closure;

class OnlyAdminIp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $client_ip = $_SERVER["HTTP_CF_CONNECTING_IP"] ?? $request->ip(); // CDN(Cloudflare) provides the real client ip, a safeguard is used to prevent critical error if CDN is removed/changed.
        $ipList = IpList::all()
            ->pluck('ip')
            ->toArray();
        if (!in_array($client_ip, $ipList)) {
            abort(401);
        }

        return $next($request);
    }
}

为了更清楚起见 - 500 路线(在 web.php 中)。

Route::group(['middleware' => 'admin.ip'], function () {


    Route::get('500', function () {
        abort(500);
    }); 

});

通过这个设置我得到Call to a member function getStatusCode() on null 提前致谢!

【问题讨论】:

    标签: laravel testing phpunit tdd laravel-5.5


    【解决方案1】:

    我想出了一个可行的解决方案。

    $request = Request::create(config('app.url') . '500', 'GET',[],[],[],['REMOTE_ADDR'=>'127.0.0.2']);
        $middleware = new OnlyAdminIp();
        $expectedStatusCode = 401;
        try {
          $middleware->handle($request, function () {});
        }catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){
            $this->assertEquals(
                $expectedStatusCode,
                $e->getStatusCode(),
                sprintf("Expected an HTTP status of %d but got %d.", $expectedStatusCode, $e->getStatusCode())
            );
        }
    

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 2018-10-23
      • 2018-03-11
      • 2018-04-11
      • 2016-12-31
      • 1970-01-01
      • 2013-10-26
      • 2014-09-11
      • 2015-01-24
      相关资源
      最近更新 更多