gpt4 book ai didi

php - mock & PHPUnit : method does not exist on this mock object

转载 作者:可可西里 更新时间:2023-10-31 22:10:07 25 4
gpt4 key购买 nike

你能告诉我问题出在哪里吗?我有一个包含以下测试的 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();
}
}

这里是 FileGenerator 类:

文件.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;
}
}

生成器.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() does not exist on this mock object

enter image description here

最佳答案

错误信息对我来说似乎很清楚。您只设置了对 put 方法的期望,但没有设置 existsexists 方法由所有代码路径中的被测类调用。

public function testGeneratorFire()
{
$fileMock = \Mockery::mock('\stats\jway\File');
$fileMock->shouldReceive('put')->with('foo.txt', 'foo bar')->once();

//Add the line below
$fileMock->shouldReceive('exists')->once()->andReturn(false);

$generator = new Generator($fileMock);
$generator->fire();
}

关于php - mock & PHPUnit : method does not exist on this mock object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37348974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com