用嘲弄来嘲笑特征方法
Mocking trait methods with mockery
我有一个特点:
trait A {
function foo() {
...
}
}
和一个 class 使用这样的特征:
class B {
use A {
foo as traitFoo;
}
function foo() {
$intermediate = $this->traitFoo();
...
}
}
我想测试 class' foo()
方法并想模拟(使用 Mockery)特征的 foo()
方法的行为。我尝试使用部分和模拟 traitFoo()
像:
$mock = Mockery::mock(new B());
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
但是没用。
这可以吗?有替代方法吗?我想测试 B::foo()
将其与特征的 foo()
实现隔离开来。
提前致谢。
您正在使用的代理模拟从模拟外部调用代理,因此无法模拟 class $this->...
中的内部调用。
如果您没有 final 方法,您仍然可以使用普通部分模拟或被动部分模拟,它扩展了模拟 class,并且没有这样的限制:
$mock = Mockery::mock(B::class)->makePartial();
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
$mock->foo();
更新:
具有非模拟特征函数的完整示例:
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());
}
}
我有一个特点:
trait A {
function foo() {
...
}
}
和一个 class 使用这样的特征:
class B {
use A {
foo as traitFoo;
}
function foo() {
$intermediate = $this->traitFoo();
...
}
}
我想测试 class' foo()
方法并想模拟(使用 Mockery)特征的 foo()
方法的行为。我尝试使用部分和模拟 traitFoo()
像:
$mock = Mockery::mock(new B());
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
但是没用。
这可以吗?有替代方法吗?我想测试 B::foo()
将其与特征的 foo()
实现隔离开来。
提前致谢。
您正在使用的代理模拟从模拟外部调用代理,因此无法模拟 class $this->...
中的内部调用。
如果您没有 final 方法,您仍然可以使用普通部分模拟或被动部分模拟,它扩展了模拟 class,并且没有这样的限制:
$mock = Mockery::mock(B::class)->makePartial();
$mock->shouldReceive('traitFoo')->andReturn($intermediate);
$mock->foo();
更新:
具有非模拟特征函数的完整示例:
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());
}
}