PHPUnit,来自 Symfony:如何在 Laravel 中正确测试缓存

问题描述 投票:0回答:1

我有一个方法可以从缓存获取信息或(如果缓存为空)向第三方服务发出长请求。我想测试我的方法来检查数据是否来自外部源的缓存。

在 Laravel 中我的代码将如下所示:

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

    if (!$response) {
        // heavy and complicated request
        $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 中使用缓存似乎有点不同,所以我的代码是这样的:

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

public function getExternalData($key)
{
    $responseDto = $this->cache->get($key, function () use ($key) {
        // heavy and complicated
        $response = $this->externalSource->getData($key);

        return $response;
    });
}

所以主要问题是:除了 Laravel,我如何编写类似的测试?

我还有其他问题:

  1. 如何测试缓存中是否有数据?我应该测试一下吗?
  2. 如何测试回调函数?
  3. 如何以正确的方式模拟缓存?
laravel symfony mocking phpunit
1个回答
0
投票

所以,第一个简单且更直接的答案是:你从不测试框架。在你的情况下,你不会测试

Cache::set
或任何类似的方法是否有效,因为你正在测试 Laravel 是否正确编码,如果
Cache::xxxxxx
有效,是的,它有效。

你想测试你自己的代码,例如,调用方法

getUser()
并且你想确保它正在使用缓存(如果存在),否则它将调用数据库并缓存它(这只是一个例子)。

以下问题:

  1. 正如我所说,您不会测试数据是否在缓存中,而是测试数据是否来自缓存
  2. 我不确定您指的是什么,请分享您要测试的回调的简洁示例,我们将为您提供帮助
  3. 你绝对可以嘲笑
    Cache
    门面,
    facade
    的想法是能够以不同的方式访问一个对象,门面的字面意思是,谷歌一下你就会明白。与测试相关,这是 Laravel 实现的美妙部分,如果你有一个外观,无论它是什么,你都可以做
    YourFacade::shouldReceive('xxxx')
    等,它会从字面上模拟该部分(你也可以 spy
    YourFacade::shouldHaveReceived('xxx')
    等) )
© www.soinside.com 2019 - 2024. All rights reserved.