Larave5中的UnitTest中间件

时间:2015-10-21 15:10:22

标签: php laravel-5.1

我有一个小型的中间件,我想为它编写一个测试..我想做两个测试:

  1. 模拟role_id与1;句柄应返回TRUE
  2. 模拟role_id 2;句柄应该返回FALSE
  3. 如何做到这一点?

    namespace App\Http\Middleware;
    
    use Closure;
    use Auth;
    use Redirect;
    
    class RedirectIfNotAdminUser {
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next) {
            if (Auth::user()->role_id != config('Roles.admin')) {
                return Redirect::action('Auth\AuthController@getLogin');
            }
    
            return $next($request);
        }
    
    }
    

    目前我运行的测试如下:

    public function testIsAdminUser() {
        $user = factory(App\User::class)->make(['role_id' => '1']); 
    
        $this->be($user);
    
        $response = $this->action('GET', 'admin\DashboardController@index');
    
        $this->assertEquals(200, $response->getStatusCode());
    }
    

    我还必须在设置中添加一行,没有它$ this-> be()不起作用

    public function setUp() { 
        $this->refreshApplication();
    }
    

    他们是更好的方法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

public function setUp()
{
    $this->redirectIfNotAdminUser = new App\Http\Middleware\RedirectIfNotAdminUser;
}

public function testIsAdminUser()
{
    // create a $user object (using a factory or something else).
    // assuming $user has a property role_id = 1.
    $this->actingAs($user);

    // create a mock of $request and $next.
    $response = $this->redirectIfNotAdminUser->handle($request, $next);

    $this->assertEquals(200, $response->getStatusCode());
}

public function testIsNotAdminUser()
{
    // create a $user object (using a factory or something else).
    // assuming $user has a property role_id = 2.
    $this->actingAs($user);

    // create a mock of $request and $next.
    $response = $this->redirectIfNotAdminUser->handle($request, $next);

    $this->assertEquals(302, $response->getStatusCode());
}

我相信中间件会返回状态代码为200的响应,如果它是OK302,则会返回。

请记住,您将成为创建User实例并让其登录的人(使用actingAs()方法)并且您将成为创建模拟人员的人$request$next将传递给您的中间件handle()方法。