Phpunit 如何模拟名称为“的方法”;方法";?
如果我有一个类Phpunit 如何模拟名称为“的方法”;方法";?,phpunit,Phpunit,如果我有一个类Foo,我可以使用下面的语法更改bar的行为 class Foo { public function method() { } public function bar() { } } 限制:名为“method”的方法上述示例仅起作用 当原始类未声明名为“method”的方法时。如果 原始类确实声明了一个名为“method”的方法 $stub->expects($this->any())->method('doSomething')->willReturn('f
Foo
,我可以使用下面的语法更改bar
的行为
class Foo {
public function method() {
}
public function bar() {
}
}
限制:名为“method”的方法上述示例仅起作用
当原始类未声明名为“method”的方法时。如果
原始类确实声明了一个名为“method”的方法
$stub->expects($this->any())->method('doSomething')->willReturn('foo');
必须使用
但我的问题是,如何更改PHPUnit中
Foo::method()
的行为?可能吗?这很好:
使用PHP7.0.9/PHPUnit 4.8.27进行测试
$stub = $this->createMock(Foo::class);
$stub->expects($this->any())
->method('bar')
->willReturn('baz');
编辑:
使用PHP7.0.9/PHPUnit 5.6.2进行测试:
public function testMethod()
{
$stub = $this->getMock(Foo::class);
$stub->expects($this->once())
->method('method')
->willReturn('works!');
$this->assertEquals('works!', $stub->method('method'));
}
仅显示第一个方法的弃用警告,但测试成功通过。PHPUnit是开源的,因此它是可能的-您必须自己进行更改。不过我怀疑这不是你的问题,你愿意缩小你的问题范围吗?@Dezza我的意思是,我如何使用PHPUnit改变
Foo::method
的行为?PHPUnit目前是否提供了这样一种方法?然后按照您在问题中提到的那样做$stub->expects($this->any())->method('method')->willReturn('foo')
它所指的“显示的示例”没有expects()
调用。我的环境是PHP7.0.12/PHPUnit 5.6.22getMock()
已被弃用,因此我使用createMock()
。但它不起作用。。。我会调查的。我会和你的环境检查确认你的第二种方法在一个简单的测试中正常工作。可能是其他因素造成了这个问题。谢谢
public function testMethodWithDeprecatedGetMock()
{
$stub = $this->getMock(Foo::class);
$stub->expects($this->once())
->method('method')
->willReturn('works!');
$this->assertEquals('works!', $stub->method('method'));
}
public function testMethodWithCreateMock()
{
$stub = $this->createMock(Foo::class);
$stub->expects($this->once())
->method('method')
->willReturn('works!');
$this->assertEquals('works!', $stub->method('method'));
}