You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPUnit:如何在Symfony中正确测试缓存机制

缓存优先的外部数据获取方法测试问题

我有一个缓存优先的外部数据获取方法:先从缓存取数据,若缓存为空则发起耗时的第三方服务请求。需要测试该方法,验证数据来源是缓存还是外部服务。

Laravel实现及测试代码

业务逻辑代码

public function getExternalData($key)
{
    $response = Cache::get($key, null);

    if (!$response) {
        // 耗时复杂的第三方请求
        $response = $this->externalSource->getData($key);

        Cache::set($key, $response);
    }

    return $response;
}

测试代码

public function testFromCache($returnData)
{
    Cache::shouldReceive('get')->once()->andReturn($returnData);
}

public function testFromSource($returnData)
{
    Cache::shouldReceive('get')->once()->andReturn(null);

    $externalSourceMock = $this->partialMock(
        Source::class,
        function (MockInterface $mock) use ($returnData) {
            $mock->shouldReceive('getData')->once()->andReturn($returnData);
        }
    );

    Cache::shouldReceive('set')->once()->andReturn(true);
}

Symfony实现代码

Symfony中缓存使用方式不同,我的业务代码如下:

public function __construct(
    private HttpClientInterface $client,
    private CacheInterface $cache,
    private LoggerInterface $logger
) {}

public function getExternalData($key)
{
    $responseDto = $this->cache->get($key, function () use ($key) {
        // 耗时复杂的第三方请求
        $response = $this->externalSource->getData($key);

        return $response;
    });
}

核心疑问

如何为Symfony版本的代码编写类似的测试?

额外问题

  • 如何测试缓存中是否存在数据?是否有必要做这个测试?
  • 如何测试回调函数?
  • 如何正确模拟Symfony的缓存组件?

内容的提问来源于stack exchange,提问作者MasteRus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:00:22