我有一个特点:
trait A {
function foo() {
...
}
}
和一个使用这样的特征的类:
class B {
use A {
foo as traitFoo;
}
function foo() {
$intermediate = $this->traitFoo();
...
}
}
我想测试课程' foo()
方法,并希望模拟(使用Mockery)特征的foo()
方法的行为。我尝试使用部分和嘲弄traitFoo()
之类的:
$mock = Mockery::mock(new B());
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
但它没有用。
有可能这样做吗?还有另一种方法吗?我想测试B::foo()
将其与特质的foo()
实施隔离开来。
提前致谢。
答案 0 :(得分:2)
The proxy mock you are using proxies calls from outside the mock, so internal calls within the class $this->...
cannot be mocked.
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());
}
}