为什么这个模拟失败了?(来自PHPUnit文件)
我使用PHPUnit文档创建了以下测试,测试失败并显示以下消息:为什么这个模拟失败了?(来自PHPUnit文件),php,mocking,phpunit,Php,Mocking,Phpunit,我使用PHPUnit文档创建了以下测试,测试失败并显示以下消息: PHP Fatal error: Call to undefined method Mock_SomeClass_97937e7a::doSomething(). 怎么了?这是文档中的示例。我正在使用phpunit4.4.0 <?php class SomeClass { } class SomeClassTest extends PHPUnit_Framework_TestCase { public fu
PHP Fatal error: Call to undefined method Mock_SomeClass_97937e7a::doSomething().
怎么了?这是文档中的示例。我正在使用phpunit4.4.0
<?php
class SomeClass
{
}
class SomeClassTest extends PHPUnit_Framework_TestCase
{
public function testStub()
{
// Create a stub for the SomeClass class.
$stub = $this->getMockBuilder('SomeClass')
->getMock();
// Configure the stub.
$stub->method('doSomething')
->willReturn('foo');
// Calling $stub->doSomething() will now return
// 'foo'.
$this->assertEquals('foo', $stub->doSomething());
}
}
某些类中缺少doSomething
方法。您不能模拟不存在的方法。以下是快照:
- 在“SomeClass”类上声明“doSomething”方法李>
- 在“getMockBuilder”之后使用“setMethods”例程
- 使用“will($this->returnValue('foo')”,而不是willReturn
这是我的密码:
class SomeClass
{
public function doSomething()
{
}
}
class StubTest extends PHPUnit_Framework_TestCase
{
public function testStub()
{
// Create a stub for the SomeClass class.
$stub = $this->getMockBuilder('SomeClass')
->setMethods(array('doSomething'))
->getMock();
// Configure the stub.
$stub->expects($this->any())
->method('doSomething')
->will($this->returnValue('foo'));
// Calling $stub->doSomething() will now return
// 'foo'.
$this->assertEquals('foo', $stub->doSomething());
}
}
谢谢你的回复,但这并没有改变一件事:(也没有使用名称空间。你是对的。问题是你的SomeClass中实际上没有doSomething()方法……我不知道我是不是瞎子,但我发誓我在那里看到过;)该死!很明显,我不能嘲笑一个不存在的方法…谢谢bbankowski。编辑你的答案,我会投票赞成。你可以模仿不存在的方法。您只需向MockBuilder添加一个setMethods
调用。这将设置要模拟的方法。因此,您的mock变成了$stub=$this->getMockBuilder('SomeClass')->setMethods(['doSomething')->getMock()代码>