我正在尝试模拟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
我尝试了很多方法,但无法解决。谢谢。
答案 0 :(得分:1)
由于Laravel's facade可能会帮助他人,因此包含了一些辅助功能,该功能可以与Mockery
测试双倍
这意味着,当您使用shouldReceive
时,可以将其与任何Mockery expectation链接,例如,在这种情况下,如果您不关心某些参数,则可以使用:
Cache::shouldReceive('put')
->with('industries.all', \Mockery::any(), \Mockery::any())
->andReturn(true);
答案 1 :(得分:0)
以防万一,可以指出您可能不会想要模拟缓存,而是实际上使用了真正的缓存。
那是因为它是仅用于测试的缓存:
通过vendor / bin / phpunit运行测试时,Laravel [....]在测试时会自动配置会话并缓存到阵列驱动程序,这意味着在测试期间不会保留任何会话或缓存数据。
https://laravel.com/docs/8.x/testing#environment
请注意,与OP的测试不同,您可能需要遵循Laravel关于您的测试类的指导来扩展其TestCase
以获得行为,例如
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase