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

Redis Mock Laravel Package

m6web/redis-mock

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev m6web/redis-mock
    

    Add to composer.json under require-dev to ensure it’s only installed for testing.

  2. 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'));
    
  3. Where to Look First:

    • README for supported commands.
    • Tests for usage examples.
    • Predis Docs for command reference (since this mocks Predis).

Implementation Patterns

Workflows

  1. 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);
    }
    
  2. 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();
        });
    }
    
  3. Seeding Mock Data: Use FLUSHDB or manual seeding before tests:

    $redis = new Client();
    $redis->flushdb(); // Reset state
    $redis->hset('user:1', 'name', 'Jane');
    

Integration Tips

  • Laravel Caching: Override Cache::store('redis') in tests:
    Cache::shouldReceive('store')->andReturn(new Client());
    
  • Queue Workers: Mock Redis for queue tests:
    $redis = new Client();
    $redis->lpush('queue:failed', json_encode(['job' => 'TestJob']));
    
  • Pub/Sub: Use publish/subscribe methods for event-driven tests.

Gotchas and Tips

Pitfalls

  1. Unsupported Commands:

    • Not all Redis commands are mocked (e.g., EVAL, SCRIPT). Check the README for the full list.
    • Workaround: Use RedisMock\Client::shouldReceive('*')->andThrow(new \RuntimeException('Unsupported command')); to fail fast.
  2. Connection Pooling:

    • The mock doesn’t simulate connection pooling. Avoid testing multi-connection logic.
  3. Time-Based Commands:

    • EXPIRE/TTL are mocked but may not behave identically to real Redis (e.g., clock skew).

Debugging

  • Assertions: Use assertEquals for values and assertTrue/assertFalse for booleans (e.g., EXISTS).
  • Logging: Enable Predis logging for debugging:
    $redis = new Client(['logger' => new \Monolog\Logger('test', [new \Monolog\Handler\TestHandler()])]);
    

Extension Points

  1. Custom Mocks: Extend RedisMock\Client to add unsupported commands:

    class CustomClient extends Client {
        public function eval($script, $keys, $args) {
            return 'mocked_result';
        }
    }
    
  2. Time Control: Mock time for TTL/EXPIRE tests by overriding the internal clock:

    $redis = new Client(['time' => time() + 1000]); // Simulate future time
    
  3. Persistence: Save/load mock state between tests using serialize()/unserialize():

    $serialized = serialize($redis->getAll());
    // Later...
    $redis->loadAll(unserialize($serialized));
    

Config Quirks

  • Predis Compatibility: Ensure your test environment uses the same Predis version as production.
  • Namespace Conflicts: If using use Redis, alias the mock to avoid conflicts:
    use RedisMock\Client as RedisMock;
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle