【问题标题】:PHP: Error in mockeryPHP:嘲弄错误
【发布时间】:2016-02-05 16:20:41
【问题描述】:

我刚刚开始按照 Jeffery way 的书“Jeffrey Way Laravel 测试解码”使用 php mockery,但我在第一次 mock 时遇到了问题。我一直在看,似乎找不到问题。

<?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);
  }
}

【问题讨论】:

  • 可以发一下Generator类的代码吗?
  • @Matteo 添加了生成器类

标签: php phpunit mockery


【解决方案1】:

你应该改变这个:

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 的期望将失败,因为输入参数不匹配。

【讨论】:

  • 这解决了您的问题还是有其他问题?
猜你喜欢
  • 2017-09-01
  • 2019-08-03
  • 2014-10-27
  • 2020-09-14
  • 2018-10-31
  • 2017-05-12
  • 2018-12-24
  • 2017-05-23
  • 2020-09-06
相关资源
最近更新 更多