缓存测试
概述
测试缓存功能是确保应用性能和可靠性的重要环节。本指南介绍如何使用 PHPUnit 测试缓存操作、Mock 缓存对象、测试缓存命中率以及并发安全性。
单元测试
测试 PSR-6 缓存池
php
<?php
declare(strict_types=1);
namespace Tests\kuiper\cache;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Ephemeral;
use PHPUnit\Framework\TestCase;
class CacheItemPoolTest extends TestCase
{
private CacheItemPool $cache;
protected function setUp(): void
{
$driver = new Ephemeral(['max_items' => 1000]);
$this->cache = new CacheItemPool($driver);
}
public function testSetAndGetItem(): void
{
$item = $this->cache->getItem('test:key');
$this->assertFalse($item->isHit());
$item->set(['name' => 'John Doe']);
$item->expiresAfter(3600);
$this->cache->save($item);
$retrievedItem = $this->cache->getItem('test:key');
$this->assertTrue($retrievedItem->isHit());
$this->assertEquals(['name' => 'John Doe'], $retrievedItem->get());
}
public function testDeleteItem(): void
{
$item = $this->cache->getItem('test:key');
$item->set('value');
$this->cache->save($item);
$this->assertTrue($this->cache->deleteItem('test:key'));
$retrievedItem = $this->cache->getItem('test:key');
$this->assertFalse($retrievedItem->isHit());
}
public function testClear(): void
{
$item1 = $this->cache->getItem('test:key1');
$item1->set('value1');
$this->cache->save($item1);
$item2 = $this->cache->getItem('test:key2');
$item2->set('value2');
$this->cache->save($item2);
$this->assertTrue($this->cache->clear());
$this->assertFalse($this->cache->hasItem('test:key1'));
$this->assertFalse($this->cache->hasItem('test:key2'));
}
public function testGetItems(): void
{
$item1 = $this->cache->getItem('test:key1');
$item1->set('value1');
$this->cache->save($item1);
$item2 = $this->cache->getItem('test:key2');
$item2->set('value2');
$this->cache->save($item2);
$items = $this->cache->getItems(['test:key1', 'test:key2', 'test:key3']);
$this->assertCount(3, $items);
$this->assertTrue($items['test:key1']->isHit());
$this->assertTrue($items['test:key2']->isHit());
$this->assertFalse($items['test:key3']->isHit());
}
public function testDeferredSave(): void
{
$item1 = $this->cache->getItem('test:key1');
$item1->set('value1');
$this->cache->saveDeferred($item1);
$item2 = $this->cache->getItem('test:key2');
$item2->set('value2');
$this->cache->saveDeferred($item2);
$this->assertTrue($this->cache->commit());
$this->assertTrue($this->cache->hasItem('test:key1'));
$this->assertTrue($this->cache->hasItem('test:key2'));
}
public function testExpiration(): void
{
$item = $this->cache->getItem('test:key');
$item->set('value');
$item->expiresAfter(1); // 1 秒后过期
$this->cache->save($item);
$this->assertTrue($this->cache->hasItem('test:key'));
sleep(2);
$this->assertFalse($this->cache->hasItem('test:key'));
}
}测试 PSR-16 简单缓存
php
<?php
declare(strict_types=1);
namespace Tests\kuiper\cache;
use kuiper\cache\ArrayCache;
use PHPUnit\Framework\TestCase;
use Psr\SimpleCache\CacheInterface;
class SimpleCacheTest extends TestCase
{
private CacheInterface $cache;
protected function setUp(): void
{
$this->cache = new ArrayCache(300, 1000);
}
public function testSetAndGet(): void
{
$this->assertTrue(
$this->cache->set('test:key', ['name' => 'John'], 3600)
);
$value = $this->cache->get('test:key');
$this->assertEquals(['name' => 'John'], $value);
}
public function testGetWithDefault(): void
{
$value = $this->cache->get('nonexistent:key', 'default');
$this->assertEquals('default', $value);
}
public function testHas(): void
{
$this->cache->set('test:key', 'value');
$this->assertTrue($this->cache->has('test:key'));
$this->assertFalse($this->cache->has('nonexistent:key'));
}
public function testDelete(): void
{
$this->cache->set('test:key', 'value');
$this->assertTrue($this->cache->delete('test:key'));
$this->assertFalse($this->cache->has('test:key'));
}
public function testSetMultiple(): void
{
$values = [
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
];
$this->assertTrue($this->cache->setMultiple($values, 3600));
$retrieved = $this->cache->getMultiple(array_keys($values));
$this->assertEquals($values, iterator_to_array($retrieved));
}
public function testGetMultipleWithDefault(): void
{
$this->cache->set('key1', 'value1');
$keys = ['key1', 'key2', 'key3'];
$values = $this->cache->getMultiple($keys, 'default');
$expected = [
'key1' => 'value1',
'key2' => 'default',
'key3' => 'default',
];
$this->assertEquals($expected, iterator_to_array($values));
}
public function testDeleteMultiple(): void
{
$this->cache->setMultiple([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
]);
$this->assertTrue(
$this->cache->deleteMultiple(['key1', 'key2'])
);
$this->assertFalse($this->cache->has('key1'));
$this->assertFalse($this->cache->has('key2'));
$this->assertTrue($this->cache->has('key3'));
}
public function testClear(): void
{
$this->cache->setMultiple([
'key1' => 'value1',
'key2' => 'value2',
]);
$this->assertTrue($this->cache->clear());
$this->assertFalse($this->cache->has('key1'));
$this->assertFalse($this->cache->has('key2'));
}
}集成测试
测试 Redis 缓存驱动
php
<?php
declare(strict_types=1);
namespace Tests\kuiper\cache;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\RedisDriver;
use PHPUnit\Framework\TestCase;
use Redis;
class RedisDriverTest extends TestCase
{
private CacheItemPool $cache;
private Redis $redis;
protected function setUp(): void
{
if (!extension_loaded('redis')) {
$this->markTestSkipped('Redis extension not loaded');
}
$this->redis = new Redis();
$connected = $this->redis->connect('127.0.0.1', 6379);
if (!$connected) {
$this->markTestSkipped('Redis server not available');
}
$driver = new RedisDriver([
'redis' => $this->redis,
'prefix' => 'test:',
]);
$this->cache = new CacheItemPool($driver);
// 注意:RedisDriver::clear(null) 会按 prefix SCAN 并删除本驱动写出的键
// (prefix + 32 位 hex),测试隔离仍建议自行清理测试前缀下的键
$this->flushTestKeys();
}
protected function tearDown(): void
{
$this->flushTestKeys();
$this->redis->close();
}
private function flushTestKeys(): void
{
$keys = $this->redis->keys('test:*');
if (!empty($keys)) {
$this->redis->del($keys);
}
}
public function testSetAndGet(): void
{
$item = $this->cache->getItem('test:key');
$item->set(['data' => 'value']);
$item->expiresAfter(3600);
$this->cache->save($item);
$retrievedItem = $this->cache->getItem('test:key');
$this->assertTrue($retrievedItem->isHit());
$this->assertEquals(['data' => 'value'], $retrievedItem->get());
}
public function testExpiration(): void
{
$item = $this->cache->getItem('test:key');
$item->set('value');
$item->expiresAfter(1);
$this->cache->save($item);
sleep(2);
$retrievedItem = $this->cache->getItem('test:key');
$this->assertFalse($retrievedItem->isHit());
}
public function testDeleteOnlyExactKey(): void
{
$item1 = $this->cache->getItem('user:1');
$item1->set('value1');
$this->cache->save($item1);
$item2 = $this->cache->getItem('user:2');
$item2->set('value2');
$this->cache->save($item2);
// RedisDriver 只删除精确匹配的键,不会按前缀级联删除
$this->assertTrue($this->cache->deleteItem('user:1'));
$this->assertFalse($this->cache->hasItem('user:1'));
$this->assertTrue($this->cache->hasItem('user:2'));
}
public function testMultiSegmentKeysMapToDistinctRedisKeys(): void
{
// RedisDriver 的普通键(全部分段都参与键名计算):
// 'user/profile/123' 与 'user/settings/123' 映射到不同的 Redis 键
$item1 = $this->cache->getItem('user/profile/123');
$item1->set('profile');
$this->cache->save($item1);
$item2 = $this->cache->getItem('user/settings/123');
$item2->set('settings');
$this->cache->save($item2);
// 两个键互不覆盖,各自命中
$this->assertTrue($this->cache->hasItem('user/profile/123'));
$this->assertTrue($this->cache->hasItem('user/settings/123'));
$this->assertEquals('profile', $this->cache->getItem('user/profile/123')->get());
$this->assertEquals('settings', $this->cache->getItem('user/settings/123')->get());
}
}测试多级缓存
php
<?php
declare(strict_types=1);
namespace Tests\kuiper\cache;
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Composite;
use kuiper\cache\stash\driver\Ephemeral;
use kuiper\cache\stash\driver\FileDriver;
use PHPUnit\Framework\TestCase;
class MultiLevelCacheTest extends TestCase
{
private CacheItemPool $cache;
private string $cacheDir;
protected function setUp(): void
{
$this->cacheDir = sys_get_temp_dir().'/test-cache-'.uniqid();
$l1Driver = new Ephemeral(['max_items' => 100]);
$l2Driver = new FileDriver(['dir' => $this->cacheDir]);
$composite = new Composite([
'drivers' => [$l1Driver, $l2Driver],
]);
$this->cache = new CacheItemPool($composite);
}
protected function tearDown(): void
{
$this->cache->clear();
array_map('unlink', glob($this->cacheDir.'/*.cache'));
rmdir($this->cacheDir);
}
public function testL1CacheHit(): void
{
$item = $this->cache->getItem('test:key');
$item->set('value');
$this->cache->save($item);
// 第一次从 L2 读取
$item1 = $this->cache->getItem('test:key');
$this->assertTrue($item1->isHit());
$this->assertEquals('value', $item1->get());
// 第二次从 L1 读取
$item2 = $this->cache->getItem('test:key');
$this->assertTrue($item2->isHit());
$this->assertEquals('value', $item2->get());
}
public function testWriteToAllLevels(): void
{
$item = $this->cache->getItem('test:key');
$item->set('value');
$this->cache->save($item);
// 验证数据写入到所有级别
$retrievedItem = $this->cache->getItem('test:key');
$this->assertTrue($retrievedItem->isHit());
$this->assertEquals('value', $retrievedItem->get());
}
public function testDeleteFromAllLevels(): void
{
$item = $this->cache->getItem('test:key');
$item->set('value');
$this->cache->save($item);
$this->assertTrue($this->cache->deleteItem('test:key'));
// 验证从所有级别删除
$this->assertFalse($this->cache->hasItem('test:key'));
}
}Mock 缓存
使用 Mock 对象测试
php
<?php
declare(strict_types=1);
namespace Tests\App\Service;
use App\Service\UserService;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
class UserServiceWithMockCacheTest extends TestCase
{
public function testGetUserFromCache(): void
{
// 创建 Mock 缓存项
$cacheItem = $this->createMock(CacheItemInterface::class);
$cacheItem->method('isHit')->willReturn(true);
$cacheItem->method('get')->willReturn([
'id' => 123,
'name' => 'John Doe',
]);
// 创建 Mock 缓存池
$cachePool = $this->createMock(CacheItemPoolInterface::class);
$cachePool->method('getItem')
->with('user:123')
->willReturn($cacheItem);
// 测试服务
$service = new UserService($cachePool);
$user = $service->getUser(123);
$this->assertEquals(['id' => 123, 'name' => 'John Doe'], $user);
}
public function testGetUserFromDatabaseWhenCacheMiss(): void
{
$cacheItem = $this->createMock(CacheItemInterface::class);
$cacheItem->method('isHit')->willReturn(false);
$cacheItem->method('set')->willReturn($cacheItem);
$cacheItem->method('expiresAfter')->willReturn($cacheItem);
$cachePool = $this->createMock(CacheItemPoolInterface::class);
$cachePool->method('getItem')
->with('user:123')
->willReturn($cacheItem);
$cachePool->method('save')->willReturn(true);
$dbMock = $this->createMock(\PDO::class);
// 配置数据库 Mock...
$service = new UserService($cachePool, $dbMock);
$user = $service->getUser(123);
$this->assertIsArray($user);
}
}使用测试替身
php
<?php
declare(strict_types=1);
namespace Tests\TestDouble;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
class InMemoryCachePool implements CacheItemPoolInterface
{
private array $storage = [];
public function getItem(string $key): CacheItemInterface
{
return new InMemoryCacheItem($key, $this->storage);
}
public function getItems(array $keys = []): iterable
{
$items = [];
foreach ($keys as $key) {
$items[$key] = $this->getItem($key);
}
return $items;
}
public function hasItem(string $key): bool
{
return isset($this->storage[$key]);
}
public function clear(): bool
{
$this->storage = [];
return true;
}
public function deleteItem(string $key): bool
{
unset($this->storage[$key]);
return true;
}
public function deleteItems(array $keys): bool
{
foreach ($keys as $key) {
unset($this->storage[$key]);
}
return true;
}
public function save(CacheItemInterface $item): bool
{
$this->storage[$item->getKey()] = [
'value' => $item->get(),
'expiration' => time() + 3600,
];
return true;
}
public function saveDeferred(CacheItemInterface $item): bool
{
return $this->save($item);
}
public function commit(): bool
{
return true;
}
}缓存命中率测试
php
<?php
declare(strict_types=1);
namespace Tests\Performance;
use kuiper\cache\ArrayCache;
use PHPUnit\Framework\TestCase;
use Psr\SimpleCache\CacheInterface;
class CacheHitRateTest extends TestCase
{
public function testCacheHitRate(): void
{
$cache = new ArrayCache(300, 1000);
// 预填充缓存
$data = [];
for ($i = 1; $i <= 100; ++$i) {
$data["key:{$i}"] = "value:{$i}";
}
$cache->setMultiple($data);
$hits = 0;
$misses = 0;
$requests = 1000;
for ($i = 0; $i < $requests; ++$i) {
$key = 'key:'.rand(1, 150); // 包含不存在的键
if ($cache->has($key)) {
++$hits;
} else {
++$misses;
}
}
$hitRate = $hits / $requests;
echo sprintf(
"Hit Rate: %.2f%% (Hits: %d, Misses: %d)\n",
$hitRate * 100,
$hits,
$misses
);
$this->assertGreaterThan(0.5, $hitRate); // 命中率应大于 50%
}
public function testBenchmarkCacheOperations(): void
{
$cache = new ArrayCache(300, 1000);
// 写入性能测试
$start = microtime(true);
for ($i = 0; $i < 1000; ++$i) {
$cache->set("key:{$i}", "value:{$i}");
}
$writeTime = microtime(true) - $start;
// 读取性能测试
$start = microtime(true);
for ($i = 0; $i < 1000; ++$i) {
$cache->get("key:{$i}");
}
$readTime = microtime(true) - $start;
echo sprintf(
"Write: %.4f sec, Read: %.4f sec\n",
$writeTime,
$readTime
);
$this->assertLessThan(1.0, $writeTime); // 写入应在 1 秒内完成
$this->assertLessThan(0.5, $readTime); // 读取应在 0.5 秒内完成
}
}并发测试
php
<?php
declare(strict_types=1);
namespace Tests\Concurrency;
use kuiper\cache\ArrayCache;
use PHPUnit\Framework\TestCase;
class ConcurrencyTest extends TestCase
{
public function testConcurrentWrites(): void
{
$cache = new ArrayCache(300, 1000);
$processes = 10;
$writesPerProcess = 100;
$pids = [];
for ($i = 0; $i < $processes; ++$i) {
$pid = pcntl_fork();
if ($pid == -1) {
$this->fail('Failed to fork process');
} elseif ($pid == 0) {
// 子进程
for ($j = 0; $j < $writesPerProcess; ++$j) {
$key = sprintf('process:%d:key:%d', $i, $j);
$cache->set($key, "value:{$j}");
}
exit(0);
} else {
$pids[] = $pid;
}
}
// 等待所有子进程完成
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
// 验证缓存写入(注意:ArrayCache 不是进程安全的)
// 实际应用应使用 Redis 等支持并发的缓存
}
public function testRaceConditionWithLock(): void
{
$cache = new ArrayCache(300, 1000);
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'test:race';
$lockKey = 'lock:'.$key;
// 进程 1
$pid1 = pcntl_fork();
if ($pid1 == 0) {
$lock = $redis->set($lockKey, 1, ['NX', 'EX' => 10]);
if ($lock) {
$cache->set($key, 'value1');
sleep(1);
$redis->del($lockKey);
}
exit(0);
}
// 进程 2
$pid2 = pcntl_fork();
if ($pid2 == 0) {
sleep(1); // 等待进程1获取锁
$lock = $redis->set($lockKey, 1, ['NX', 'EX' => 10]);
if ($lock) {
$cache->set($key, 'value2');
$redis->del($lockKey);
}
exit(0);
}
// 等待子进程
pcntl_waitpid($pid1, $status);
pcntl_waitpid($pid2, $status);
// 验证只有一个进程成功写入
$value = $cache->get($key);
$this->assertContains($value, ['value1', 'value2']);
}
}测试最佳实践
1. 使用测试专用的缓存配置
xml
<!-- phpunit.xml -->
<php>
<env name="CACHE_NAMESPACE" value="test"/>
<env name="CACHE_MEMORY_ENABLED" value="true"/>
<env name="CACHE_FILE_DIR" value="/tmp/test-cache"/>
</php>2. 清理测试数据
php
<?php
abstract class CacheTestCase extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->clearCache();
}
protected function tearDown(): void
{
$this->clearCache();
parent::tearDown();
}
abstract protected function clearCache(): void;
}3. 使用数据提供者
php
<?php
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Ephemeral;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
class CacheDriverTest extends TestCase
{
public static function cacheDriverProvider(): array
{
return [
// Ephemeral 实现的是 DriverInterface,
// 必须包一层 CacheItemPool 才能满足 CacheItemPoolInterface 类型参数
'ephemeral' => [new CacheItemPool(new Ephemeral())],
// 注意:ArrayCache 实现的是 PSR-16 CacheInterface,
// 不是 DriverInterface,不能放进这个数据提供器
// 'redis' => [new CacheItemPool(new RedisDriver([...]))],
];
}
/**
* @dataProvider cacheDriverProvider
*/
public function testSetAndGet(CacheItemPoolInterface $cache): void
{
$item = $cache->getItem('test:key');
$item->set('value');
$cache->save($item);
$retrieved = $cache->getItem('test:key');
$this->assertTrue($retrieved->isHit());
$this->assertEquals('value', $retrieved->get());
}
}4. 测试边界条件
php
<?php
use kuiper\cache\ArrayCache;
use kuiper\cache\stash\InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class CacheEdgeCaseTest extends TestCase
{
public function testEmptyKey(): void
{
// 空键不含任何非空分段,KeyValidator 校验失败抛 InvalidArgumentException
// (kuiper\cache\stash\InvalidArgumentException,同时实现 PSR-6 / PSR-16 标记接口)
$cache = new ArrayCache();
$this->expectException(InvalidArgumentException::class);
$cache->get('');
}
public function testVeryLongKey(): void
{
$cache = new ArrayCache();
$longKey = str_repeat('a', 1000);
$this->assertTrue($cache->set($longKey, 'value'));
$this->assertEquals('value', $cache->get($longKey));
}
public function testSpecialCharactersInKey(): void
{
$cache = new ArrayCache();
$specialKey = 'test:key:with:special/chars\\and:spaces';
$this->assertTrue($cache->set($specialKey, 'value'));
$this->assertEquals('value', $cache->get($specialKey));
}
public function testNullValue(): void
{
$cache = new ArrayCache();
$this->assertTrue($cache->set('test:key', null));
$this->assertNull($cache->get('test:key'));
}
public function testLargeValue(): void
{
$cache = new ArrayCache();
$largeValue = str_repeat('x', 1024 * 1024); // 1MB
$this->assertTrue($cache->set('test:key', $largeValue));
$this->assertEquals($largeValue, $cache->get('test:key'));
}
}性能基准测试
php
<?php
class CachePerformanceBenchmark
{
public function benchmark(CacheInterface $cache, int $iterations = 10000): array
{
// 写入性能
$start = microtime(true);
for ($i = 0; $i < $iterations; ++$i) {
$cache->set("key:{$i}", "value:{$i}");
}
$writeTime = microtime(true) - $start;
$writeOpsPerSec = $iterations / $writeTime;
// 读取性能
$start = microtime(true);
for ($i = 0; $i < $iterations; ++$i) {
$cache->get("key:{$i}");
}
$readTime = microtime(true) - $start;
$readOpsPerSec = $iterations / $readTime;
return [
'write_ops_per_sec' => $writeOpsPerSec,
'read_ops_per_sec' => $readOpsPerSec,
'write_time' => $writeTime,
'read_time' => $readTime,
];
}
}测试清单
完成缓存测试时,确保覆盖以下方面:
- 基本读写操作
- 缓存未命中处理
- 过期时间设置
- 批量操作
- 删除操作
- 清空操作
- 边界条件(空键、长键、特殊字符)
- 大数据值
- 并发访问
- 缓存命中率
- 性能基准测试
- Mock 对象测试
- 集成测试