为什么这个模拟失败了? (来自 PHPUnit 文档)
Why is this mock failing? (from PHPUnit doc)
我使用 PHPUnit 文档创建了以下测试,但失败并显示以下消息:
PHP Fatal error: Call to undefined method Mock_SomeClass_97937e7a::doSomething().
怎么了?这是文档中的示例。我正在使用 PHPUnit 4.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 中丢失。您不能模拟不存在的方法。
这是快照:
- 在您的 "SomeClass" class 上声明 "doSomething" 方法。
- 在"getMockBuilder"
之后使用"setMethods"例程
- 不要使用 willReturn,而是使用 "will($this->returnValue('foo'))"。
这是我的代码:
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());
}
}
我使用 PHPUnit 文档创建了以下测试,但失败并显示以下消息:
PHP Fatal error: Call to undefined method Mock_SomeClass_97937e7a::doSomething().
怎么了?这是文档中的示例。我正在使用 PHPUnit 4.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 中丢失。您不能模拟不存在的方法。
这是快照:
- 在您的 "SomeClass" class 上声明 "doSomething" 方法。
- 在"getMockBuilder" 之后使用"setMethods"例程
- 不要使用 willReturn,而是使用 "will($this->returnValue('foo'))"。
这是我的代码:
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());
}
}