Installation:
composer require --dev m6web/redis-mock
Add to composer.json under require-dev to ensure it’s only installed for testing.
First Use Case:
Replace Predis\Client in your test setup with RedisMock\Client:
use RedisMock\Client;
$redis = new Client();
$redis->set('foo', 'bar');
$this->assertEquals('bar', $redis->get('foo'));
Where to Look First:
Test Isolation:
Use RedisMock\Client in unit tests to avoid hitting a real Redis instance:
public function testCacheLogic()
{
$redis = new Client();
$redis->set('user:1:data', ['name' => 'John']);
$data = $redis->get('user:1:data');
$this->assertEquals(['name' => 'John'], $data);
}
Mocking Redis in Feature Tests:
Replace Laravel’s Redis connection in phpunit.xml or TestCase bootstrapping:
protected function setUp(): void
{
$this->app->bind('redis', function () {
return new Client();
});
}
Seeding Mock Data:
Use FLUSHDB or manual seeding before tests:
$redis = new Client();
$redis->flushdb(); // Reset state
$redis->hset('user:1', 'name', 'Jane');
Cache::store('redis') in tests:
Cache::shouldReceive('store')->andReturn(new Client());
$redis = new Client();
$redis->lpush('queue:failed', json_encode(['job' => 'TestJob']));
publish/subscribe methods for event-driven tests.Unsupported Commands:
EVAL, SCRIPT). Check the README for the full list.RedisMock\Client::shouldReceive('*')->andThrow(new \RuntimeException('Unsupported command')); to fail fast.Connection Pooling:
Time-Based Commands:
EXPIRE/TTL are mocked but may not behave identically to real Redis (e.g., clock skew).assertEquals for values and assertTrue/assertFalse for booleans (e.g., EXISTS).$redis = new Client(['logger' => new \Monolog\Logger('test', [new \Monolog\Handler\TestHandler()])]);
Custom Mocks:
Extend RedisMock\Client to add unsupported commands:
class CustomClient extends Client {
public function eval($script, $keys, $args) {
return 'mocked_result';
}
}
Time Control:
Mock time for TTL/EXPIRE tests by overriding the internal clock:
$redis = new Client(['time' => time() + 1000]); // Simulate future time
Persistence:
Save/load mock state between tests using serialize()/unserialize():
$serialized = serialize($redis->getAll());
// Later...
$redis->loadAll(unserialize($serialized));
use Redis, alias the mock to avoid conflicts:
use RedisMock\Client as RedisMock;
How can I help you explore Laravel packages today?