gpt4 book ai didi

php - 如何使用 Mockery 模拟构造函数

转载 作者:可可西里 更新时间:2023-11-01 12:39:17 25 4
gpt4 key购买 nike

我需要测试,代码创建了一个具有特定参数的类的新实例:

$bar = new ProgressBar($output, $size);

我试图创建一个别名 mock 并为 __construct 方法设置期望值,但它没有用:

$progressBar = \Mockery::mock('alias:' . ProgressBar::class);
$progressBar->shouldReceive('__construct')
->with(\Mockery::type(OutputInterface::class), 3)
->once();

这个期望永远不会满足:

Mockery\Exception\InvalidCountException: Method __construct(object(Mockery\Matcher\Type), 3) from Symfony\Component\Console\Helper\ProgressBar should be called exactly 1 times but called 0 times.

你知道如何用 Mockery 测试这个吗?

最佳答案

好吧,你不能模拟构造函数。相反,您需要稍微修改您的生产代码。我可以从描述中猜到你有这样的东西:

class Foo {
public function bar(){
$bar = new ProgressBar($output, $size);
}
}

class ProgressBar{
public function __construct($output, $size){
$this->output = $output;
$this->size = $size;
}
}

这不是世界上最好的代码,因为我们有耦合依赖。 (例如,如果 ProgressBar 是值对象,那完全可以)。

首先,您应该将 ProgressBarFoo 分开测试。因为这样你就可以测试 Foo 你不需要关心 ProgressBar 是如何工作的。您知道它有效,您对此进行了测试。

但是如果你仍然想测试它的实例化(出于任何原因),这里有两种方法。对于这两种方式,您都需要提取 new ProggresBar

class Foo {
public function bar(){
$bar = $this->getBar($output, $size);
}

public function getBar($output, $size){
return new ProgressBar($output, $size)
}
}

方式一:

class FooTest{
public function test(){
$foo = new Foo();
$this->assertInstanceOf(ProgressBar::class, $foo->getBar(\Mockery::type(OutputInterface::class), 3));
}
}

方式二:

class FooTest{
public function test(){
$mock = \Mockery::mock(Foo::class)->makePartial();
$mock->shouldReceive('getBar')
->with(\Mockery::type(OutputInterface::class), 3)
->once();
}
}

测试愉快!

关于php - 如何使用 Mockery 模拟构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575154/

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