PHP:嘲弄中的错误

时间:2016-02-04 17:33:24

标签: php phpunit mockery

我刚开始使用php mockery遵循Jeffery方式书“Jeffrey Way Laravel Testing Decoded”,但我在第一次模拟时遇到了问题。我一直在看它似乎无法找到问题。

<?php
namespace BB8\Tests;

use BB8\App\Generator;
use BB8\App\File;
use Mockery;
class GeneratorTest extends \PHPUnit_Framework_TestCase
{
    public function testMockery()
    {
        $mockedFile = Mockery::mock(File::class);
        $mockedFile->shouldReceive('put')
                    ->with('foo.txt', 'foo bar bar')
                    ->once();
        $generator = new Generator($mockedFile);
        $generator->fire();
    }
}

抛出的错误是

Mockery\Exception\NoMatchingExpectationException: No matching handler found 
for Mockery_0_BB8_App_File::put("foo.txt", "foo bar"). 
Either the method was unexpected or its arguments matched 
no expected argument list for this method

我已经实现了所有方法但它不起作用。

我需要帮助,似乎无法找出问题所在。

生成器类

namespace BB8\App;

class Generator
{
  protected $file;

  public function __construct(File $file)
  {
    $this->file = $file;
  }

  protected function getContent()
  {
    return 'foo bar';
  }

  public function fire()
  {
    $content = $this->getContent();
    $this->file->put('foo.txt', $content);
  }
}

1 个答案:

答案 0 :(得分:0)

你应该改变这个:

public function testMockery()
{
    $mockedFile = Mockery::mock(File::class);
    $mockedFile->shouldReceive('put')
                ->with('foo.txt', 'foo bar bar')
                ->once();
    $generator = new Generator($mockedFile);
    $generator->fire();
}

到此:

public function testMockery()
{
    $mockedFile = Mockery::mock(File::class);
    $mockedFile->shouldReceive('put')
                ->with('foo.txt', 'foo bar')
                ->once();
    $generator = new Generator($mockedFile);
    $generator->fire();
}

问题是getContent()将返回'foo bar',而不是'foo bar bar',因此您对put的期望会因为输入参数不匹配而失败。