gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:48:16 25 4
gpt4 key购买 nike

我已经在服务提供者中注册了一个单例(在其构造函数中使用了 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 测试中,如何用模拟的 Client 类替换 app()->make(\App\Client\Channel::class);但仍然在测试中测试验证功能?

最佳答案

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

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',
]);
}

请务必查看 mock 文档:

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

关于laravel - 在 Laravel 验证方法中使用单例进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50312395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com