【发布时间】:2013-12-17 20:48:34
【问题描述】:
如何创建一个模拟类(不仅仅是一个模拟对象),其方法在实例化时会返回一个可预测的值?
在下面的代码中,我正在测试一个更大的概念(accounts->preauthorize()),但我需要模拟对象 Lookup 以便我可以获得可预测的测试结果。
我正在使用 PHPUnit 和 CakePHP,如果这很重要的话。这是我的情况:
// The system under test
class Accounts
{
public function preauthorize()
{
$obj = new Lookup();
$result = $obj->get();
echo $result; // expect to see 'abc'
// more work done here
}
}
// The test file, ideas borrowed from question [13389449][1]
class AccountsTest
{
$foo = $this->getMockBuilder('nonexistent')
->setMockClassName('Lookup')
->setMethods(array('get'))
->getMock();
// There is now a mock Lookup class with the method get()
// However, when my code creates an instance of Lookup and calls get(),
// it returns NULL. It should return 'abc' instead.
// I expected this to make my instances return 'abc', but it doesn't.
$foo->expects($this->any())
->method('get')
->will($this->returnValue('abc'));
// Now run the test on Accounts->preauthorize()
}
【问题讨论】:
标签: php unit-testing phpunit