Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Redis Mock Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require --dev josiasmontag/laravel-redis-mock
    

    Add to config/app.php under providers (if not auto-discovered):

    JosiasMontag\LaravelRedisMock\RedisMockServiceProvider::class,
    
  2. 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);
        }
    }
    
  3. 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);
    }
    

Implementation Patterns

Common Workflows

  1. 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
    ]);
    
  2. Mocking Pipeline/Transactions Use mockRedisPipeline for multi-command sequences:

    $this->mockRedisPipeline([
        'set' => ['key1', 'value1'],
        'set' => ['key2', 'value2'],
        'get' => ['key1', 'value1'],
    ]);
    
  3. Dynamic Responses Use closures for dynamic mocking:

    $this->mockRedis('incr', function ($key) {
        return $key === 'counter' ? 42 : 0;
    });
    
  4. Integration with Laravel Features

    • Cache Integration:
      $this->mockRedis('get', 'cache:key', 'mocked-cache-value');
      
    • Queues (Redis Driver):
      $this->mockRedis('lpush', 'queue:default', 'job-payload');
      $this->mockRedis('rpop', 'queue:default', 'job-payload');
      
  5. 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);
    }
    
  6. Testing Rate Limiting

    $this->mockRedis('get', 'rate_limit:user:1', 5);
    $this->mockRedis('incr', 'rate_limit:user:1');
    

Laravel 13+ Compatibility

  • TestCase Updates: Ensure your test classes extend Laravel\Lumen\Testing\TestCase or Illuminate\Foundation\Testing\TestCase (Laravel 13+).
  • Redis Connection Binding: Use the updated binding syntax if migrating from older Laravel versions:
    $this->mockRedis('get', ..., connection: 'cache'); // Laravel 13+ style
    

Gotchas and Tips

Pitfalls

  1. Global State

    • Mocks persist across tests unless cleared. Use RedisMock::clear() or scope mocks per test.
    • Fix: Wrap mocks in setUp/tearDown or use unique keys:
      $this->mockRedis("test_{$method}:get", ...);
      
  2. Case Sensitivity

    • Redis commands are case-insensitive in Laravel (Redis::get vs redis:get), but the mock expects exact matches.
    • Fix: Use lowercase in mocks:
      $this->mockRedis('get', ...); // Not 'GET'
      
  3. Pipeline Order

    • Mocked pipelines execute in the order they are defined, not the order of actual calls.
    • Fix: Define pipelines to match expected call sequences.
  4. Connection Binding

    • The package defaults to the default connection. Override with:
      $this->mockRedis('get', ..., connection: 'cache'); // Laravel 13+ style
      
  5. Closure Context

    • Closures receive the raw arguments passed to Redis, not parsed ones. For hget, use:
      $this->mockRedis('hget', function ($hash, $key) {
          return $hash === 'user:1' && $key === 'name' ? 'John' : null;
      });
      

Debugging Tips

  1. Verify Mocks Use RedisMock::getMocks() to inspect active mocks:

    $this->assertArrayHasKey('get', RedisMock::getMocks());
    
  2. Check for Overrides If a mock isn’t working, another test may have overridden it. Use unique keys or clear mocks.

  3. Real Redis Fallback Disable mocks in a test with:

    RedisMock::disable();
    

    Re-enable with RedisMock::enable().

  4. Logging Enable debug logging for the package:

    config(['redis-mock.debug' => true]);
    

Extension Points

  1. Custom Mock Handlers Extend the mock system by adding a custom handler:

    RedisMock::extend('customCommand', function ($args) {
        return "custom-result-{$args[0]}";
    });
    
  2. Mocking Redis Events Simulate Pub/Sub or events:

    $this->mockRedis('publish', 'channel', 'message');
    $this->mockRedis('subscribe', 'channel', ['message']);
    
  3. Integration with Factories Combine with Laravel factories for complex test data:

    $user = User::factory()->create();
    $this->mockRedis('get', "user:{$user->id}", $user->toArray());
    
  4. Performance Testing Mock Redis to simulate slow responses:

    $this->mockRedis('get', function () {
        sleep(2); // Simulate latency
        return 'slow-value';
    });
    
  5. Laravel 13+ Features

    • Test Helpers: Leverage Laravel 13's refreshTestingInMemoryServices() if needed:
      public function testWithFreshRedis() {
          $this->refreshTestingInMemoryServices();
          $this->mockRedis('flushdb', true);
      }
      
    • Pest Integration: If using Pest, ensure compatibility with Laravel 13's test helpers.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor