[英]Mocking trait methods with mockery
I have a trait: 我有一个特点:
trait A {
function foo() {
...
}
}
and a class that uses the trait like this: 和一个使用这样的特征的类:
class B {
use A {
foo as traitFoo;
}
function foo() {
$intermediate = $this->traitFoo();
...
}
}
I want to test the class' foo()
method and want to mock (with Mockery) the behavior of the trait's foo()
method. 我想测试类的'
foo()
方法,并希望模拟(使用Mockery)trait的foo()
方法的行为。 I tried using a partial and mocking traitFoo()
like: 我尝试使用部分和
traitFoo()
如:
$mock = Mockery::mock(new B());
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
But it doesn't work. 但它不起作用。
Is it possible to do this? 是否有可能做到这一点? Is there an alternative way?
还有另一种方法吗? I want to test
B::foo()
isolating it from the trait's foo()
implementation. 我想测试
B::foo()
将它与trait的foo()
实现隔离开来。
Thanks in advance. 提前致谢。
The proxy mock you are using proxies calls from outside the mock, so internal calls within the class $this->...
cannot be mocked. 代理模拟你在模拟外部使用代理调用,因此类
$this->...
内部调用不能被模拟。
If you have no final methods, you still can use normal partial mock or a passive partial mock, which extends the mocked class, and don't have such limitations: 如果你没有最终方法,你仍然可以使用普通的部分模拟或被动部分模拟,它扩展了模拟类,并且没有这样的限制:
$mock = Mockery::mock(B::class)->makePartial();
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
$mock->foo();
UPDATE: 更新:
The full example with non-mocked trait functions: 具有非模拟特征函数的完整示例:
use Mockery as m;
trait A
{
function foo()
{
return 'a';
}
function bar()
{
return 'd';
}
}
class B
{
use A {
foo as traitFoo;
bar as traitBar;
}
function foo()
{
$intermediate = $this->traitFoo();
return "b$intermediate" . $this->traitBar();
}
}
class BTest extends \PHPUnit_Framework_TestCase
{
public function testMe()
{
$mock = m::mock(B::class)->makePartial();
$mock->shouldReceive('traitFoo')->andReturn('c');
$this->assertEquals('bcd', $mock->foo());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.