Last active
June 26, 2023 02:32
-
-
Save tralves/4aaf9439e1cc12c213e3f7106f317c3f to your computer and use it in GitHub Desktop.
Override the Authentication when using dingo/api, when testing the Api with PhpUnit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Entities\User; | |
class ProfileApiTest extends TestCase | |
{ | |
/** | |
* @test | |
* | |
* Get user profile. | |
* | |
* Given There there is an authenticated user. | |
* When GET /profile is called. | |
* Then return the user data. | |
*/ | |
public function it_returns_user_profile() | |
{ | |
//given | |
$user = factory(User::class)->create(); | |
$this->actingAsApi($user); | |
//when | |
$response = $this->call('GET', '/profile'); | |
// then | |
$this->seeJson(['id' => $user->id]) | |
->seeJson(['name' => $user->name]) | |
->seeJson(['email' => $user->email]); | |
} | |
// TODO: test other /profile endpoints | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Providers\AppServiceProvider; | |
class TestCase extends Laravel\Lumen\Testing\TestCase | |
{ | |
/** | |
* Creates the application. | |
* | |
* @return \Laravel\Lumen\Application | |
*/ | |
public function createApplication() | |
{ | |
$unitTesting = true; | |
$testEnvironment = 'testing'; | |
return require __DIR__ . '/../bootstrap/app.php'; | |
} | |
public function setUp() | |
{ | |
parent::setUp(); | |
$this->baseUrl = env('API_SCHEME', 'http') . "://" . env('API_DOMAIN'); | |
} | |
/** | |
* Sets the API user. | |
* | |
* @param App\Entities\User $user | |
* @return $this | |
*/ | |
protected function actingAsApi($user) | |
{ | |
// mock service middleware | |
$auth = Mockery::mock('Dingo\Api\Http\Middleware\Auth[handle]', | |
[ | |
Mockery::mock('Dingo\Api\Routing\Router'), | |
Mockery::mock('Dingo\Api\Auth\Auth'), | |
]); | |
$auth->shouldReceive('handle') | |
->andReturnUsing(function ($request, \Closure $next) { | |
return $next($request); | |
}); | |
$this->app->instance('Dingo\Api\Http\Middleware\Auth', $auth); | |
$auth = Mockery::mock('Dingo\Api\Auth\Auth[user]', | |
[ | |
app('Dingo\Api\Routing\Router'), | |
app('Illuminate\Container\Container'), | |
[], | |
]); | |
$auth->shouldReceive('user') | |
->andReturnUsing(function () use ($user) { | |
return $user; | |
}); | |
$this->app->instance('Dingo\Api\Auth\Auth', $auth); | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment