在 Laravel 中的验证方法中使用单例进行单元测试

Jen*_*ski 3 validation phpunit laravel

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

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

我有一个验证方法:

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

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

Nit*_*mar 6

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

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',
         ]);
}
Run Code Online (Sandbox Code Playgroud)

请务必查看嘲笑文档:

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