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

Technical Evaluation

Architecture Fit

  • Strengths:

    • Directly addresses test isolation by mocking Eloquent queries without requiring a repository pattern, aligning with Laravel’s native ORM.
    • Reduces database dependency in unit tests, improving test speed and reliability.
    • Leverages Laravel’s Service Container and Eloquent abstractions, minimizing architectural disruption.
    • MIT license enables easy adoption with no legal barriers.
  • Weaknesses:

    • No repository pattern enforcement: May encourage anti-patterns (e.g., direct model instantiation in tests) if not paired with a testing strategy.
    • Limited to Eloquent: Incompatible with non-ORM data layers (e.g., raw SQL, third-party APIs).
    • Mock granularity: May not cover complex query builder scenarios (e.g., whereHas, with) as thoroughly as dedicated testing libraries like Mockery + DatabaseMigrations.
  • Key Use Cases:

    • Unit testing services/controllers interacting with Eloquent models.
    • CI/CD optimization by reducing database spin-up time.
    • Legacy codebases where refactoring to a repository pattern is costly.

Integration Feasibility

  • Low-risk for Laravel apps:
    • Single composer dependency (imanghafoori/eloquent-mockery).
    • Minimal configuration (no migrations, no service provider bootstrapping).
    • Works with Laravel 9+ (PHP 8.1+) and Eloquent out of the box.
  • Potential Conflicts:
    • Existing mocking libraries: May require deprecating Mockery or PHPUnit extensions if overlapping functionality exists.
    • Test doubles: Could clash with factories (e.g., Laravel\Pest\Factories) if not configured to coexist.

Technical Risk

Risk Area Severity Mitigation Strategy
Test flakiness Medium Pair with RefreshDatabase or DatabaseTransactions for edge cases.
Query complexity Low Supplement with Mockery for unsupported Eloquent methods.
Version compatibility Low Monitor Laravel/Eloquent breaking changes (e.g., query builder APIs).
Team adoption Medium Provide migration guides and examples.

Key Questions

  1. Testing Strategy:
    • Does the team already use a repository pattern? If not, will this package encourage better separation?
  2. Query Coverage:
    • Are there unsupported Eloquent features (e.g., hydrate, macro queries) critical to the test suite?
  3. Toolchain Compatibility:
    • How will this integrate with existing tools (e.g., Pest, PHPUnit, Laravel Dusk)?
  4. Performance Impact:
    • Will mocking reduce test suite execution time significantly, or are bottlenecks elsewhere (e.g., API calls)?
  5. Maintenance:
    • Who will handle updates if the package stagnates (no dependents, last release 2024-06-21)?

Integration Approach

Stack Fit

  • Primary Fit:
    • Laravel applications using Eloquent for data access.
    • Teams prioritizing unit test speed and isolation.
  • Secondary Fit:
    • Projects with minimalist testing (no repository pattern, no factories).
  • Non-Fit:
    • Apps using raw SQL, non-ORM data layers, or heavily coupled services.
    • Teams requiring behavior-driven development (BDD) with living documentation.

Migration Path

  1. Assessment Phase:
    • Audit existing tests for Eloquent dependencies (identify high-impact queries).
    • Benchmark current test suite execution time (baseline for optimization).
  2. Pilot Integration:
    • Start with critical path tests (e.g., API endpoints, core services).
    • Example migration:
      // Before: Database-dependent test
      public function test_user_creation()
      {
          $user = User::create([...]);
          $this->assertDatabaseHas('users', [...]);
      }
      
      // After: Mocked test
      use Imanghafoori\EloquentMockery\EloquentMockery;
      
      public function test_user_creation()
      {
          EloquentMockery::mock(User::class, [
              'create' => fn($data) => new User($data)
          ]);
          $user = User::create([...]);
          $this->assertInstanceOf(User::class, $user);
      }
      
  3. Full Rollout:
    • Replace database assertions with mock validations where applicable.
    • Deprecate DatabaseTransactions in favor of mocks for unit tests (keep for integration tests).

Compatibility

Component Compatibility Status Notes
Laravel 9+ ✅ Full Tested against latest Laravel versions.
PHP 8.1+ ✅ Full Requires named arguments.
Eloquent ✅ Full Covers basic CRUD and query builder.
Mockery ⚠️ Partial May overlap; prefer one or the other.
Pest/PHPUnit ✅ Full Works as a test helper.
Factories ⚠️ Conditional Avoid mixing with EloquentMockery.

Sequencing

  1. Phase 1: Mock simple queries (create, find, update).
  2. Phase 2: Extend to relationships (belongsTo, hasMany).
  3. Phase 3: Handle edge cases (e.g., firstOrFail, pluck).
  4. Phase 4: Integrate with CI/CD to measure impact on test speed.

Operational Impact

Maintenance

  • Pros:
    • Reduced flakiness: Tests pass without database dependencies.
    • Easier debugging: Mocks provide deterministic outputs.
    • Lower CI costs: Faster test execution reduces cloud compute usage.
  • Cons:
    • Mock drift: Tests may become outdated if business logic changes (mitigate with contract tests).
    • Maintenance burden: Requires updating mocks when Eloquent APIs evolve.
    • False positives: Over-mocking may hide real issues (e.g., missing validations).

Support

  • Developer Experience:
    • Positive: Developers can iterate quickly without waiting for database setup.
    • Negative: Requires discipline to avoid over-mocking (e.g., mocking save() instead of testing validation).
  • Onboarding:
    • Low barrier: Simple API (EloquentMockery::mock()).
    • Documentation gap: README lacks advanced examples (e.g., mocking events, observers).
  • Troubleshooting:
    • Common issues:
      • Mocks not persisting across test cases (use beforeEach in Pest/PHPUnit).
      • Conflicts with RefreshDatabase (disable for mocked tests).

Scaling

  • Performance:
    • Test speed: 10–100x faster than database-driven tests (depends on query complexity).
    • Memory: Minimal overhead (mocks are in-memory).
  • Team Scaling:
    • Parallelization: Mocks enable true parallel test execution (no DB locks).
    • Isolation: Reduces "works on my machine" issues caused by DB state.
  • Limitations:
    • Integration tests: Still require a database (use DatabaseMigrations or Testcontainers).
    • Complex queries: May need hybrid approaches (e.g., mock simple queries, use DB for complex ones).

Failure Modes

Failure Mode Impact Mitigation
Over-mocking Tests pass but hide bugs. Enforce a test pyramid (more unit, fewer integration tests).
Mock-Logic Drift Mocks break when business logic changes. Use feature flags or contract tests.
False Assumptions Mocks assume implementation details. Prefer behavior-based assertions (e.g., "user was created" vs. "ID=1").
Toolchain Conflicts Clashes with factories/DB tools. Isolate mocks to specific test files.

Ramp-Up

  • Training:
    • 1-hour workshop: Demo migration from DB tests to mocks.
    • Cheat sheet: Common patterns (e.g., mocking relationships, events).
  • Adoption Metrics:
    • Goal: 80% of unit tests use EloquentMockery within 3 months.
    • KPIs:
      • Test suite execution time reduced by 50%.
      • Zero flaky tests in CI.
  • Resistance Points:
    • Senior devs: May prefer "real" DB tests for confidence.
      • Counter: Show side-by-side benchmarks.
    • QA teams: May distrust mocks for edge cases.
      • Counter: Reserve integration
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
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