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

标签 php unit-testing mocking phpunit mockery

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

相关文章:

c# - 测试代理消息

php - 使用不同的值更新多行 SQL

php - 以人类可读格式排列的日期

unit-testing - mock 去。有简单的方法吗?

带有 Jasmine/Karma 的 Angular Mock 字段/属性

java - 使用 Spring 框架单例 bean 进行单元测试

symfony - 如何使用 Doctrine 实体创建测试而不持久化它们(如何设置 id)

php - 更新帖子/行,而不是创建新的

php - 将 Laravel Socialite 与 API 一起使用?

c# - 如何在模拟对象内创建模拟对象?