【问题标题】:Laravel Feature Testing. Cache mocking not working! CacheManager::driver(), but no expectations were specifiedLaravel 功能测试。缓存模拟不起作用! CacheManager::driver(),但没有指定期望
【发布时间】:2019-10-07 15:27:41
【问题描述】:

当我使用单元测试缓存模拟测试我的应用程序时,效果很好。但是当我尝试通过功能测试来测试我的 api 时,我遇到了一个异常。

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 嘲弄\异常\BadMethodCallException:收到 Mockery_2_Illuminate_Cache_CacheManager::driver(),但没有期望 被指定了

在其他单元测试中完全相同的模拟工作没有错误。

【问题讨论】:

  • 我猜你已经完成了,但我会在调用缓存之前通过 die-dumping 来检查相同的代码是否正在执行,以确保它是一个 Mocking 问题。实际的 Cache 被触动了吗?
  • dd(123);在缓存无例外地工作之前
  • 你是否覆盖了phpunit.xml 文件中的一些环境变量?
  • 仅 DB_CONNECTION

标签: laravel testing mocking phpunit laravel-5.8


【解决方案1】:

我在这里找到了答案 - https://github.com/laravel/framework/issues/10803#issuecomment-401611084%23issuecomment-401611084

    $cacheDriver = app('cache')->driver();
    Cache::shouldReceive('driver')->andReturn($cacheDriver);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-29
    • 2015-10-21
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多