Warm tip: This article is reproduced from serverfault.com, please click

phpunit-无法在Laravel中模拟Cache :: put()门面

(phpunit - Unable to mock Cache::put() facade in Laravel)

发布于 2018-08-04 05:22:48

我正在尝试模仿Cache::put()门面。但这给了我一个错误。我尝试了不同的方法,但无法弄清楚。

public function testGetAllFromDatabase()
{
    $industry = new Industry();

    Cache::shouldReceive('has')
        ->once()
        ->with('industries.all')
        ->andReturn(false);

    Cache::shouldReceive('put')
        ->with('industries.all', '', 0)
        ->andReturn(true);

    $this->industryMock
        ->shouldReceive('all')
        ->once()
        ->andReturn(array_reverse($this->industries));

    $this->app->instance(Industry::class, $this->industryMock);

    $industryRepository = new IndustryRepository();
    $all = $industryRepository->all();
    dd($all);
    $this->assertContains( $this->industries[2], $all);
}

但是,当我执行它时,发生以下错误。

$ vendor/bin/phpunit
PHPUnit 7.2.7 by Sebastian Bergmann and contributors.

...E                                                                4 / 4 (100%)

Time: 3.76 seconds, Memory: 12.00MB

There was 1 error:

1) Tests\Unit\RepositoriesTests\IndustryRepositoryTest::testGetAllFromDatabase
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_Illuminate_Cache_CacheManager::put('industries.all', object(Illuminate\Database\Eloquent\Collection), '1440'). Either the method was unexpected or its arguments matched no expected argument list for this method

Objects: ( array (
  'Illuminate\\Database\\Eloquent\\Collection' =>
  array (
    'class' => 'Illuminate\\Database\\Eloquent\\Collection',
    'properties' =>
    array (
    ),
  ),
))

F:\development\consulting.local\src\vendor\mockery\mockery\library\Mockery\ExpectationDirector.php:92
F:\development\consulting.local\src\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:223
F:\development\consulting.local\src\app\Repositories\IndustryRepository.php:30
F:\development\consulting.local\src\tests\Unit\RepositoriesTests\IndustryRepositoryTest.php:81

我已经尝试了很多方法,但是无法解决它。谢谢你。

Questioner
Achintha Samindika
Viewed
0
apokryfos 2018-08-04 15:14:43

由于它可能对他人有帮助,因此Laravel的外观包括了辅助功能,该功能允许在Mockery测试两次之后进行交换

这意味着,当你使用a时shouldReceive,可以将其与任何Mockery期望进行链接,例如,在这种情况下,如果你不关心某些参数,则可以使用:

Cache::shouldReceive('put')
    ->with('industries.all', \Mockery::any(), \Mockery::any())
    ->andReturn(true);