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 Database Mock Laravel Package

mpyw/laravel-database-mock

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Mocking Layer: Fits well in a test-driven development (TDD) or behavior-driven development (BDD) pipeline, particularly for unit/integration tests targeting database interactions.
  • Isolation: Enables decoupling of database dependencies in tests, reducing reliance on real databases (MySQL, PostgreSQL, etc.) during CI/CD.
  • Laravel Ecosystem: Designed specifically for Laravel’s Eloquent ORM and Query Builder, leveraging Laravel’s connection abstraction.
  • Experimental Risk: Marked as experimental, meaning API stability is unproven—potential for breaking changes in future versions.

Integration Feasibility

  • PDO Mocking: Replaces Laravel’s underlying PDO connections with Mockery-based mocks, allowing fine-grained control over SQL queries and responses.
  • Compatibility: Works with Laravel 11/12 and PHP 8.2+, aligning with modern Laravel stacks.
  • Dependency on mockery-pdo: Requires an alpha version of mpyw/mockery-pdo, introducing external dependency risk (unproven stability).
  • Test Coverage: High coverage (per Coveralls) suggests robustness in core functionality, but real-world edge cases (e.g., complex transactions, raw SQL) may need validation.

Technical Risk

  • Alpha Dependency: mockery-pdo is in alpha, risking instability or missing features.
  • Performance Overhead: Mocking introduces runtime overhead in tests (though negligible in CI/CD).
  • Limited Adoption: Only 6 stars and 0 dependents suggest low community validation; may lack long-term support.
  • Edge Cases: Untested scenarios (e.g., stored procedures, batch inserts, custom query builders) could expose gaps.
  • Carbon Integration: Relies on Carbon::setTestNow() for timestamp mocking—may conflict with existing test setups.

Key Questions

  1. Stability: How does the package handle real-world Laravel queries (e.g., DB::raw(), subqueries, joins)?
  2. Performance: Does mocking introduce significant test slowdowns in large suites?
  3. Maintenance: Will mockery-pdo reach stable 1.0? What’s the upgrade path?
  4. Alternatives: How does this compare to Laravel’s built-in DatabaseMigrations, Factory testing, or PestPHP’s mocking?
  5. CI/CD Impact: Can it fully replace database tests in CI, or are some tests still needed?
  6. Debugging: How easy is it to inspect failed mocks (e.g., unexpected queries)?
  7. Transaction Support: Does it handle database transactions (rollbacks, commits) correctly?
  8. Security: Are there SQL injection risks when mocking dynamic queries?

Integration Approach

Stack Fit

  • Ideal For:
    • Unit/Integration Tests: Mocking database layers in CI/CD pipelines to avoid flaky tests.
    • Legacy System Refactoring: Isolating database-dependent logic during migrations.
    • API Contract Testing: Validating query responses without hitting a real DB.
  • Less Suitable For:
    • End-to-End (E2E) Tests: Mocking may not cover full system behavior (e.g., triggers, stored procs).
    • Performance Testing: Mocks don’t replicate real database latency.
    • Teams Using PestPHP: May overlap with Pest’s built-in mocking (e.g., fake()).

Migration Path

  1. Pilot Phase:
    • Start with non-critical test suites (e.g., feature branches).
    • Replace DatabaseTransactions or RefreshDatabase with mocks for fast feedback.
  2. Incremental Adoption:
    • Replace simple queries (SELECT/INSERT/UPDATE) first.
    • Gradually introduce for complex queries (joins, aggregations).
  3. Dependency Management:
    • Pin mockery-pdo to a specific alpha version to avoid surprises.
    • Monitor for stable releases of mockery-pdo.

Compatibility

  • Laravel Compatibility:
    • Works with Laravel 11/12 out of the box.
    • May require adjustments for custom query builders or third-party ORMs.
  • PHP Version:
    • PHP 8.2+ required; ensure CI/CD nodes are updated.
  • Mockery Integration:
    • Requires Mockery 1.6.12+; conflicts possible if using PHPUnit’s built-in mocks.
  • Carbon Timestamps:
    • Uses Carbon::setTestNow()—ensure no conflicts with existing time-mocking tools.

Sequencing

  1. Setup:
    • Install via Composer:
      composer require mpyw/laravel-database-mock mpyw/mockery-pdo:dev-alpha
      
    • Configure Mockery in phpunit.xml:
      <php>
          <env name="MOCKERY" value="1"/>
      </php>
      
  2. Basic Mocking:
    • Replace DatabaseMigrations with DBMock in test setup:
      public function setUp(): void
      {
          parent::setUp();
          DBMock::mockPdo(); // Global mock or per-test
      }
      
  3. Query Mocking:
    • Define expectations before running queries:
      $pdo = DBMock::mockPdo();
      $pdo->shouldSelect('SELECT * FROM users')->shouldFetchAllReturns([...]);
      
  4. Advanced Use Cases:
    • Mock transactions, prepared statements, or errors as needed.
    • Extend for custom query builders if required.

Operational Impact

Maintenance

  • Test Reliability:
    • Pros: Eliminates database flakiness (e.g., schema changes, network issues).
    • Cons: Mocks must be kept in sync with real queries—drift risk if queries change.
  • Debugging:
    • Harder to debug than real DB errors (e.g., "Query not mocked" vs. SQL syntax error).
    • May require logging mocked queries for troubleshooting.
  • Dependency Updates:
    • Alpha dependency (mockery-pdo) requires close monitoring for stability.
    • Laravel version upgrades may need revalidation.

Support

  • Community Support:
    • Limited (6 stars, no dependents). Issues may go unanswered.
    • GitHub Discussions or GitHub Issues are primary support channels.
  • Documentation:
    • Basic examples provided, but edge cases (e.g., raw SQL, events) undocumented.
    • May need internal runbooks for complex setups.
  • Vendor Lock-in:
    • Custom mocking logic may tightly couple to this package—migration cost if switching tools.

Scaling

  • Test Suite Growth:
    • Faster tests (no DB spin-up) scales well for large suites.
    • Memory usage may increase with complex mocks (e.g., nested queries).
  • Parallel Testing:
    • Mocks are thread-safe (unlike real DBs), enabling parallel test execution.
  • CI/CD Impact:
    • Reduces test time significantly (e.g., from 5 mins → 30 sec for DB-heavy suites).
    • May increase CI costs if mocks are overly complex (e.g., deep query nesting).

Failure Modes

Failure Scenario Impact Mitigation
Unmocked query executed Test fails unpredictably Use DBMock::verifyAllMocks()
mockery-pdo breaks Tests fail silently Pin to a specific alpha version
Query expectations mismatch Flaky tests Log all mocked queries in CI
Carbon timestamp conflicts Incorrect created_at values Isolate timestamp mocking per test
Complex SQL (e.g., raw queries) Unsupported syntax Fall back to real DB for edge cases
Package abandonment No future updates Fork or seek alternatives (e.g., Pest)

Ramp-Up

  • Learning Curve:
    • Moderate: Requires understanding of Mockery and Laravel’s query structure.
    • Steep for complex queries (e.g., dynamic SQL, stored procs).
  • Onboarding Steps:
    1. Train team on Mockery basics and DBMock syntax.
    2. Start small: Replace 1–2 test classes first.
    3. Document patterns: E.g., "How to mock a WHERE IN clause."
    4. CI Validation: Ensure mocks work in parallel test runs.
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle