josiasmontag/laravel-redis-mock
Drop-in Redis mock for Laravel tests using Redis PHP Mock. Adds a “mock” Redis client so you can run test suites without a running Redis server. Enable via REDIS_CLIENT=mock in .env.testing/phpunit.xml; works with Testbench for package dev.
Installation
composer require --dev josiasmontag/laravel-redis-mock
Add to config/app.php under providers (if not auto-discovered):
JosiasMontag\LaravelRedisMock\RedisMockServiceProvider::class,
Basic Usage
In a test file, use the RedisMock facade or trait:
use JosiasMontag\LaravelRedisMock\Facades\RedisMock;
use JosiasMontag\LaravelRedisMock\Traits\RedisMockTrait;
// Facade
RedisMock::shouldReceive('get')->once()->andReturn('mocked-value');
// Trait
class MyTest extends TestCase {
use RedisMockTrait;
public function testRedisGet() {
$this->mockRedis('get', 'mocked-value');
$value = Redis::get('key');
$this->assertEquals('mocked-value', $value);
}
}
First Use Case Mock Redis calls in unit tests to avoid hitting a real Redis instance:
public function testCacheLogic() {
$this->mockRedis('set', true); // Mock successful set
$this->mockRedis('get', 'user:123'); // Mock get response
$result = $this->app->make(CacheService::class)->getUser(123);
$this->assertEquals('user:123', $result);
}
Mocking Specific Commands
// Mock a single command
$this->mockRedis('hget', 'profile:1:name', 'John Doe');
// Mock multiple commands
$this->mockRedis([
'get' => 'value',
'exists' => true,
'del' => 1, // Return 1 for successful deletion
]);
Mocking Pipeline/Transactions
Use mockRedisPipeline for multi-command sequences:
$this->mockRedisPipeline([
'set' => ['key1', 'value1'],
'set' => ['key2', 'value2'],
'get' => ['key1', 'value1'],
]);
Dynamic Responses Use closures for dynamic mocking:
$this->mockRedis('incr', function ($key) {
return $key === 'counter' ? 42 : 0;
});
Integration with Laravel Features
$this->mockRedis('get', 'cache:key', 'mocked-cache-value');
$this->mockRedis('lpush', 'queue:default', 'job-payload');
$this->mockRedis('rpop', 'queue:default', 'job-payload');
Testing Jobs
public function testJobExecution() {
$this->mockRedis('lpush', 'queue:jobs', json_encode(['job' => 'SendEmailJob']));
$this->mockRedis('rpop', 'queue:jobs', json_encode(['job' => 'SendEmailJob']));
$this->assertQueued(SendEmailJob::class);
}
Testing Rate Limiting
$this->mockRedis('get', 'rate_limit:user:1', 5);
$this->mockRedis('incr', 'rate_limit:user:1');
Laravel\Lumen\Testing\TestCase or Illuminate\Foundation\Testing\TestCase (Laravel 13+).$this->mockRedis('get', ..., connection: 'cache'); // Laravel 13+ style
Global State
RedisMock::clear() or scope mocks per test.setUp/tearDown or use unique keys:
$this->mockRedis("test_{$method}:get", ...);
Case Sensitivity
Redis::get vs redis:get), but the mock expects exact matches.$this->mockRedis('get', ...); // Not 'GET'
Pipeline Order
Connection Binding
default connection. Override with:
$this->mockRedis('get', ..., connection: 'cache'); // Laravel 13+ style
Closure Context
hget, use:
$this->mockRedis('hget', function ($hash, $key) {
return $hash === 'user:1' && $key === 'name' ? 'John' : null;
});
Verify Mocks
Use RedisMock::getMocks() to inspect active mocks:
$this->assertArrayHasKey('get', RedisMock::getMocks());
Check for Overrides If a mock isn’t working, another test may have overridden it. Use unique keys or clear mocks.
Real Redis Fallback Disable mocks in a test with:
RedisMock::disable();
Re-enable with RedisMock::enable().
Logging Enable debug logging for the package:
config(['redis-mock.debug' => true]);
Custom Mock Handlers Extend the mock system by adding a custom handler:
RedisMock::extend('customCommand', function ($args) {
return "custom-result-{$args[0]}";
});
Mocking Redis Events Simulate Pub/Sub or events:
$this->mockRedis('publish', 'channel', 'message');
$this->mockRedis('subscribe', 'channel', ['message']);
Integration with Factories Combine with Laravel factories for complex test data:
$user = User::factory()->create();
$this->mockRedis('get', "user:{$user->id}", $user->toArray());
Performance Testing Mock Redis to simulate slow responses:
$this->mockRedis('get', function () {
sleep(2); // Simulate latency
return 'slow-value';
});
Laravel 13+ Features
refreshTestingInMemoryServices() if needed:
public function testWithFreshRedis() {
$this->refreshTestingInMemoryServices();
$this->mockRedis('flushdb', true);
}
How can I help you explore Laravel packages today?