gpt4 book ai didi

php - Laravel:如何模拟依赖注入(inject)类方法

转载 作者:行者123 更新时间:2023-12-01 16:26:06 26 4
gpt4 key购买 nike

我正在使用GitHub API通过Laravel API Wrapper 。我创建了一个依赖注入(inject)类。如何模拟 App\Http\GitHub.php 类中的 exists 方法?

App\Http\GitHub.php:

use GrahamCampbell\GitHub\GitHubManager;

class Github
{
public $username;

public $repository;

public function __construct($username, $repository, GitHubManager $github)
{
$this->username = $username;

$this->repository = $repository;

$this->github = $github;
}

public static function make($username, $repository)
{
return new static($username, $repository, app(GitHubManager::class));
}

/**
* Checks that a given path exists in a repository.
*
* @param string $path
* @return bool
*/
public function exists($path)
{
return $this->github->repository()->contents()->exists($this->username, $this->repository, $path);
}
}

测试:

    use App\Http\GitHub;
public function test_it_can_check_if_github_file_exists()
{
$m = Mockery::mock(GitHub::class);
$m->shouldReceive('exists')->andReturn(true);
app()->instance(GitHub::class, $m);

$github = GitHub::make('foo', 'bar');

$this->assertTrue($github->exists('composer.lock'));
}

运行此测试实际上会命中 API,而不仅仅是返回模拟的 true 值,我在这里做错了什么?

最佳答案

这里存在树问题,即实例化对象的方式。您在模拟对象上调用两个方法并将其绑定(bind)到错误的实例的方式。

依赖注入(inject)

静态方法通常是一种反模式,构造函数参数不符合容器的工作方式,因此您将无法使用 resolve(Github::class);。通常 Laravel 类通过使用 setter 来解决这个问题。

class Github
{
public $username;

public $repository;

public $github;

public function __construct(GitHubManager $github)
{
$this->github = $github;
}

public function setUsername(string $username) {
$this->username = $username;

return $this;
}

public function setRepository(string $repository) {
$this->repository = $repository;

return $this;
}
}

现在您可以使用以下方法调用您的代码。

resolve(Github::class)->setUsername('Martin')->setRepository('my-repo')->exists();

方法的链接

这里有两个对模拟对象的调用,它们是链接的,因此您应该创建一个与此类似的模拟链。现在模拟对象不知道内容,因此失败。

$m = Mockery::mock(GitHub::class);

$m->shouldReceive('contents')
->andReturn($m);

$m->shouldReceive('exists')
->with('Martin', 'my-repo', 'your-path')
->once()
->andReturn(true);

绑定(bind)实例

使用容器时,它会根据类自动加载它,因此如果使用 app() 解析,以下代码将依赖注入(inject) GithubManager resolve() 或在构造函数中。

public function __construct(GithubManager $manager)

此代码将在上面的解析示例中注入(inject) GithubManager,但在您的示例中,您将其绑定(bind)到 GitHub 类,该类不会自动加载,并且您应该始终模拟链中最远的类。因此你的实例绑定(bind)应该是。

app()->instance(GitHubManager::class, $m);

关于php - Laravel:如何模拟依赖注入(inject)类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60342730/

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