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

Eloquent Mockery Laravel Package

imanghafoori/eloquent-mockery

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require imanghafoori/eloquent-mockery --dev
    

    Add to composer.json under require-dev to avoid production bloat.

  2. First Use Case: Mock a simple User model query in a test:

    use Imanghafoori\EloquentMockery\EloquentMockery;
    
    public function test_find_user()
    {
        EloquentMockery::mock(User::class, [
            'find(1)' => User::factory()->make(['name' => 'Test User'])
        ]);
    
        $user = User::find(1);
        $this->assertEquals('Test User', $user->name);
    }
    
  3. Key Files:

    • tests/TestCase.php: Ensure EloquentMockery is available via use.
    • config/testing.php: Check for any test-specific configurations (though this package is config-free).

Implementation Patterns

Core Workflows

  1. Mocking Queries:

    // Mock a single method call
    EloquentMockery::mock(User::class, [
        'find(1)' => User::factory()->make(),
        'where("active", 1)->get()' => User::factory()->count(3)->make()
    ]);
    
    // Mock with dynamic parameters
    EloquentMockery::mock(User::class, [
        'findOrFail(?)' => fn($id) => User::factory()->make(['id' => $id])
    ]);
    
  2. Conditional Mocking: Use closures for dynamic responses:

    EloquentMockery::mock(User::class, [
        'whereHas("posts", fn($q) => $q->where("published", 1))' => fn() => User::factory()->count(2)->make()
    ]);
    
  3. Resetting Mocks: Clear mocks between tests:

    EloquentMockery::reset(User::class);
    
  4. Integration with Factories: Combine with Laravel’s factories for realistic test data:

    EloquentMockery::mock(User::class, [
        'find(1)' => User::factory()->state(['verified_at' => now()])->create()
    ]);
    
  5. Mocking Relationships:

    EloquentMockery::mock(User::class, [
        'posts' => Post::factory()->count(2)->make()
    ]);
    

Best Practices

  • Scope Mocks: Limit mocks to specific test methods to avoid side effects.
  • Use beforeEach: Reset mocks in setUp() or beforeEach():
    public function setUp(): void
    {
        EloquentMockery::reset(User::class);
        parent::setUp();
    }
    
  • Test Isolation: Avoid mocking the same model across unrelated tests.

Gotchas and Tips

Pitfalls

  1. Global State:

    • Mocks persist until explicitly reset. Forgetting to reset can cause flaky tests.
    • Fix: Use EloquentMockery::reset() or wrap mocks in beforeEach.
  2. Method Signature Mismatches:

    • Closures must match the exact method signature (e.g., findOrFail(?) vs. findOrFail($id)).
    • Fix: Use fn($id) => ... for dynamic parameters.
  3. Lazy Loading:

    • Mocked relationships (e.g., posts) are eager-loaded by default. For lazy loading, use:
      EloquentMockery::mock(User::class, [
          'posts' => fn() => Post::factory()->count(1)->make()
      ]);
      
  4. Database Transactions:

    • If using transactions, ensure mocks are reset after each test to avoid conflicts.
  5. Static Method Mocking:

    • The package primarily mocks instance methods. For static methods (e.g., User::boot()), use PHP’s Mockery directly.

Debugging Tips

  • Verify Mocks:
    $this->assertTrue(EloquentMockery::isMocked(User::class));
    $this->assertEquals(1, EloquentMockery::mockCount(User::class));
    
  • Log Mocked Calls: Enable debug mode (if available) or use dd() to inspect mocked responses:
    EloquentMockery::mock(User::class, [
        'find(1)' => fn() => dd('Mocked call triggered') ?: User::factory()->make()
    ]);
    

Extension Points

  1. Custom Mock Providers: Extend the package by creating a trait or helper for reusable mock setups:

    trait UserMocks
    {
        protected function mockActiveUser()
        {
            EloquentMockery::mock(User::class, [
                'find(1)' => User::factory()->active()->make()
            ]);
        }
    }
    
  2. Integration with Pest: Use Pest’s beforeEach for cleaner mock management:

    beforeEach(function () {
        EloquentMockery::reset(User::class);
    });
    
  3. Performance: For large-scale mocking, consider caching factory responses or using Mockery directly for complex scenarios.

  4. Edge Cases:

    • Mock save() or delete() methods to simulate persistence:
      EloquentMockery::mock(User::class, [
          'save()' => true, // Simulate successful save
          'delete()' => null // Simulate soft delete
      ]);
      
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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