【问题标题】:Unit Testing with a singleton inside a validation method in Laravel在 Laravel 的验证方法中使用单例进行单元测试
【发布时间】:2018-10-23 01:20:22
【问题描述】:

我在服务提供者中注册了一个单例(在其构造函数中使用 Guzzle 客户端):

public function register()
{
    $this->app->singleton(Channel::class, function ($app) {
        return new ChannelClient(new Client([
            'http_errors'=> false,
            'timeout' => 10,
            'connect_timeout' => 10
        ]));
    });
}

我有一个验证方法:

 public static function validateChannel($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator)
    {
        $dataloader = app()->make(\App\Client\Channel::class);
        if($dataloader->search($value)){
            return true;
        }
    }

在 PHPUnit 测试中,如何将 app()->make(\App\Client\Channel::class); 替换为模拟的 Client 类,但仍要在测试中测试验证功能?

【问题讨论】:

    标签: laravel validation phpunit


    【解决方案1】:

    要在您的测试中使用模拟,您可以执行以下操作:

    public function test_my_controller () {
        // Create a mock of the Random Interface
        $mock = Mockery::mock(RandomInterface::class);
    
        // Set our expectation for the methods that should be called
        // and what is supposed to be returned
        $mock->shouldReceive('someMethodName')->once()->andReturn('SomeNonRandomString');
    
        // Tell laravel to use our mock when someone tries to resolve
        // an instance of our interface
        $this->app->instance(RandomInterface::class, $mock);
    
        $this->post('/api/v1/do_things', ['email' => $this->email])
             ->seeInDatabase('things', [
                 'email' => $this->email, 
                 'random' => 'SomeNonRandomString',
             ]);
    }
    

    请务必查看嘲弄文档:

    http://docs.mockery.io/en/latest/reference/expectations.html

    【讨论】:

    • 谢谢!这行代码真的帮了我大忙: $this->app->instance(RandomInterface::class, $mock);知道我可以在函数中引用它时传递模拟。非常感谢
    • 我也有同样的问题,但根源在于 phpunit mocks,它与 laravel Mockery 有冲突
    猜你喜欢
    • 2017-05-23
    • 2019-05-10
    • 2016-05-05
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2014-12-20
    • 2012-01-08
    相关资源
    最近更新 更多