问题
When I test my application with unit-testing cache moking works well. But when I try test my api through feature tests I got an exception.
public function testGet()
{
Cache::shouldReceive('rememberForever')->times(5)->andReturn([]);
Cache::shouldReceive('has')
->once()
->andReturn(false);
Cache::shouldReceive('forever')
->once()
->andReturn([]);
$response = $this->getJson('/api/table/get');
$response->assertOk();
$responseArr = $response->getOriginalContent();
$this->assertEmpty($responseArr['table']);
}
Tests\Feature\Controller\API\Site\TableApiControllerTest::testGet Mockery\Exception\BadMethodCallException: Received Mockery_2_Illuminate_Cache_CacheManager::driver(), but no expectations were specified
Exactly the same mocking in other unit-tests works without errors.
回答1:
I found answer here - https://github.com/laravel/framework/issues/10803#issuecomment-401611084%23issuecomment-401611084
$cacheDriver = app('cache')->driver();
Cache::shouldReceive('driver')->andReturn($cacheDriver);
来源:https://stackoverflow.com/questions/56234834/laravel-feature-testing-cache-mocking-not-working-cachemanagerdriver-but