【问题标题】:Test Laravel Service Provider with phpunit使用 phpunit 测试 Laravel 服务提供者
【发布时间】:2021-11-01 10:52:05
【问题描述】:

我正在尝试在 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 的实例,并且可以测试是否调用了 register 和 boot 方法,但是现在我需要测试 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 方法?

【问题讨论】:

  • 我的回答对您的问题有帮助还是您还有其他问题?

标签: laravel phpunit


【解决方案1】:

在这种特定情况下,他们在模拟上使用了数组索引,而它不能。

我猜您可以改为解析数组并获得所需的功能。

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

【讨论】:

  • 这是一个非常独特的问题,我的解决方案有点老套,但让我们看看我们是否可以让它发挥作用。
猜你喜欢
  • 2016-10-06
  • 2017-07-06
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
相关资源
最近更新 更多