使用phpunit测试Laravel服务提供商



我正在尝试在phpunit中测试我的身份验证服务提供商。provider中的代码是:

class AuthServiceProvider extends ServiceProvider {
public function register() {
}
public function boot() {
$this->app['auth']->viaRequest('api', function ($request) {
if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
return null;
} else {
return new User("some params");
}
}
}
}
}

目前我已经模拟了Application::class的实例,可以测试是否调用了注册和启动方法,但现在我需要测试viaRequest方法中的代码。我尝试了以下操作:

class AuthServiceProviderTest extends TestCase
{
protected $app_mock;
protected $provider;
public function setUp(): void
{
$this->setUpMocks();
$this->provider = new AuthServiceProvider($this->app_mock);
parent::setUp();
}
private function setUpMocks(){
$this->app_mock = Mockery::mock(Application::class);
}
public function testIfProviderIsConstructed(){
$this->assertInstanceOf(AuthServiceProvider::class, $this->provider);
}
public function testIfviaRequestIsCalled(){
$this->app_mock->shouldReceive("viaRequest")
->once();
$this->provider->boot();
}
}

但是得到一个错误:

Error : Cannot use object of type Mockery_0_Illuminate_Contracts_Foundation_Application as array

你能告诉我如何测试viaRequest方法吗?

在这个特定的例子中,他们在mock上使用数组索引,而mock不能使用数组索引。

我猜你将能够解析一个数组,而不是得到所需的功能。

$this->provider = new AuthServiceProvider(['auth' => $this->app_mock]);

最新更新