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

时间:2018-05-13 03:06:18

标签: laravel validation phpunit

我在服务提供商(在其中使用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但仍测试测试中的验证函数?

1 个答案:

答案 0 :(得分:2)

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

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