【发布时间】:2023-03-26 21:55:01
【问题描述】:
我想测试 Auth 外观,当调用 createUserProivder() 方法时,返回我的用户提供程序。
问题在于,使用以下代码,注释掉的部分,AuthManager 仍然是原始的,而不是模拟的。
对于未注释的部分,我收到一个错误:Mockery\Exception\BadMethodCallException : Method Mockery_2_Illuminate_Auth_AuthManager::validate() does not exist on this mock object
我不知道如何测试它。
我想测试一个自定义的守卫行为,它在 Guard 的 validated() 方法被调用时调用 UserProvider,因此我需要模拟 Auth 门面,因为它是返回 User Provider 的门面。
public function testUserIsAuthenticatedWhenUserProviderFindsCredentialsMatch()
{
$userId = Uuid::uuid();
$user = new User($userId);
$userProvider = new UserProvider($user);
// $this->partialMock(AuthManager::class, function ($mock) use ($userProvider) {
// $mock->shouldReceive('createUserProvider')
// ->once()
// ->andReturn($userProvider);
// });
Auth::shouldReceive('createUserProvider')
->once()
->andReturn($userProvider);
$result = $this->app['auth']->validate(['dummy' => 123]);
测试方法:
/**
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = []): bool
{
$this->user = $this->provider->retrieveByCredentials($credentials);
return (bool)$this->user;
}
服务提供商:
class LaravelServiceProvider extends AuthServiceProvider
{
/**
* Register any application authentication / authorization services.
*
* @return void
*/
public function boot()
{
Auth::extend(
'jwt',
function ($app, $name, array $config) {
$moduleConfig = $app['config'];
return new JWTAuthGuard(
Auth::createUserProvider($config['provider']),
$this->app['request'],
new JWTHelper()
);
}
);
}
}
【问题讨论】:
标签: laravel testing integration-testing mockery laravel-facade