首页 文章

使用Laravel Passport范围进行单元测试

提问于
浏览
1

我们!当我试图用Laravel和Passport进行一些单元测试时,我遇到了问题 .

我有一些受 auth:api 中间件保护的路由,但其他一些受Passport scope 中间件保护 .

例如,这是我的单元测试之一:

public function testGetPublishedPost(){

   $user = factory(\App\User::class)->create();
   $this->actingAs($user, 'api');


   $article1 = factory(\App\Article::class)->create();
   $article2 = factory(\App\Article::class)->create();
   $article3 = factory(\App\Article::class)->create( ['published' => false);


   $json = $this->call('get', '/api/articles');
   $articles = json_decode($json->getContent());

   $this->assertEquals(200, $json->getStatusCode());
   $this->assertEquals(2, count($articles));
}

所有这一切都正常,但现在,我想做一些测试,包括范围 .

我怎样才能做到这一点 ?

谢谢 !

1 回答

  • 1

    如果您不关心测试auth中间件,可以通过定义到您的函数的临时路由来完全跳过护照身份验证:

    Route::get('/_test/api/articles', 'App\Http\Controllers\YourApiController@yourArticleFunction');
    
    //Gain access to Auth:user() in your api controller
    $this->be($user);
    
    //Call the temporary route
    $response = $this->call('GET', '/_test/api/articles');
    

相关问题