【发布时间】:2016-09-17 20:29:35
【问题描述】:
你能告诉我问题出在哪里吗?我有一个文件 GeneratorTest.php,其中包含以下测试:
<?php
namespace stats\Test;
use stats\jway\File;
use stats\jway\Generator;
class GeneratorTest extends \PHPUnit_Framework_TestCase
{
public function tearDown() {
\Mockery::close();
}
public function testGeneratorFire()
{
$fileMock = \Mockery::mock('\stats\jway\File');
$fileMock->shouldReceive('put')->with('foo.txt', 'foo bar')->once();
$generator = new Generator($fileMock);
$generator->fire();
}
public function testGeneratorDoesNotOverwriteFile()
{
$fileMock = \Mockery::mock('\stats\jway\File');
$fileMock->shouldReceive('exists')
->once()
->andReturn(true);
$fileMock->shouldReceive('put')->never();
$generator = new Generator($fileMock);
$generator->fire();
}
}
这里是 File 和 Generator 类:
文件.php:
class File
{
public function put($path, $content)
{
return file_put_contents($path, $content);
}
public function exists($file_path)
{
if (file_exists($file_path)) {
return true;
}
return false;
}
}
Generator.php:
class Generator
{
protected $file;
public function __construct(File $file)
{
$this->file = $file;
}
protected function getContent()
{
// simplified for demo
return 'foo bar';
}
public function fire()
{
$content = $this->getContent();
$file_path = 'foo.txt';
if (! $this->file->exists($file_path)) {
$this->file->put($file_path, $content);
}
}
}
所以,当我运行这些测试时,我收到以下消息:BadMethodCallException: Method ... ::exists() 在这个模拟对象上不存在。
【问题讨论】:
-
尝试将
withAnyArgs()添加到文件的模拟中,例如:$fileMock->shouldReceive('exists') ->once()->withAnyArgs() ->andReturn(true); -
我试过了,同样的问题依然存在。
标签: php unit-testing mocking phpunit mockery