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

  • Test Isolation: Perfectly aligns with unit/integration testing by replacing real database interactions with controlled mocks, enabling deterministic test execution.
  • Laravel-Specific: Leverages Laravel’s connection abstraction and Eloquent/Query Builder, reducing boilerplate for database-dependent tests.
  • Experimental Constraints: Designed for TDD/BDD workflows but lacks production-grade stability due to its alpha-stage dependency (mockery-pdo).
  • Query Coverage: Supports CRUD operations, read replicas, and basic transactions, but gaps may exist for complex queries (e.g., raw SQL, stored procedures).

Integration Feasibility

  • PDO Replacement: Seamlessly intercepts PDO calls at the Laravel connection level, requiring minimal code changes.
  • Mockery Dependency: Mandates Mockery 1.6.12+, which may conflict with PHPUnit’s native mocking or other testing libraries.
  • Carbon Integration: Relies on Carbon::setTestNow() for timestamp mocking, which could clash with existing time-mocking strategies (e.g., PestPHP, Carbon’s built-in testing tools).
  • Laravel Version Lock: Strictly tied to Laravel 11/12, limiting adoption in older or newer stacks.

Technical Risk

  • Alpha Dependency Risk: mockery-pdo is pre-release, risking breaking changes or missing features (e.g., prepared statements, error handling).
  • Test Flakiness: Mocks must precisely match real queries; mismatches could lead to false positives/negatives in tests.
  • Performance Overhead: Mocking introduces runtime reflection, potentially slowing down tests in large suites (though negligible in CI).
  • Limited Validation: No dependents and low stars suggest unproven real-world use cases (e.g., microservices, high-concurrency systems).
  • Edge Cases: Untested scenarios include:
    • Database events (e.g., Model::observers, Model::booted).
    • Custom query builders or third-party ORMs.
    • Connection pooling or replica routing edge cases.

Key Questions

  1. Query Complexity: How well does it handle nested queries, CTEs, or dynamic SQL (e.g., DB::raw())?
  2. Transaction Support: Does it properly mock savepoints, explicit transactions, or rollbacks?
  3. Error Simulation: Can it simulate database errors (e.g., deadlocks, timeouts) realistically?
  4. CI/CD Impact: Will it reduce test execution time sufficiently to justify adoption?
  5. Debugging Tools: Are there built-in tools to inspect mocked queries or diagnose failures?
  6. Migration Path: What’s the upgrade path if mockery-pdo stabilizes or changes API?
  7. Alternatives: How does it compare to PestPHP’s fake(), Laravel’s DatabaseMocker, or custom mocking?
  8. Security: Does it sanitize inputs when mocking dynamic queries (e.g., ? placeholders)?

Integration Approach

Stack Fit

  • Best For:
    • Unit/Integration Tests: Ideal for isolating database logic in Laravel apps (e.g., API controllers, CLI commands).
    • Legacy Refactoring: Enables incremental testing of monolithic apps by mocking database layers.
    • CI/CD Optimization: Reduces database provisioning costs by eliminating real DB dependencies in tests.
  • Less Suitable For:
    • E2E Tests: Mocks may not cover full system behavior (e.g., triggers, stored procedures).
    • Performance Testing: Real database responses are needed for latency/throughput benchmarks.
    • Teams Without Mockery: Requires Mockery expertise, which may increase onboarding time.

Migration Path

  1. Pilot Phase:
    • Start with non-critical test suites (e.g., feature branches for new endpoints).
    • Replace DatabaseTransactions or RefreshDatabase with mocks for faster feedback.
  2. Incremental Adoption:
    • Phase 1: Mock simple queries (SELECT/INSERT/UPDATE) in unit tests.
    • Phase 2: Extend to integration tests (e.g., API feature tests).
    • Phase 3: Replace database-heavy tests in CI/CD (e.g., nightly builds).
  3. Dependency Management:
    • Pin mockery-pdo to a specific alpha version (e.g., dev-alpha).
    • Monitor for stable releases and upgrade cautiously.

Compatibility

  • Laravel Compatibility:
    • Officially supports Laravel 11/12; may work with 10.x but untested.
    • Custom query builders may require additional mocking logic.
  • PHP Version:
    • PHP 8.2+ required; ensure CI/CD nodes and local dev environments are updated.
  • Mockery Integration:
    • Conflicts possible with PHPUnit’s native mocks; ensure Mockery is the primary mocking tool.
  • Carbon Timestamps:
    • Uses Carbon::setTestNow(); conflicts may arise if tests already mock time (e.g., PestPHP).

Sequencing

  1. Setup:
    • Install dependencies:
      composer require mpyw/laravel-database-mock mpyw/mockery-pdo:dev-alpha --dev
      
    • Configure Mockery in phpunit.xml:
      <php>
          <env name="MOCKERY" value="1"/>
          <autoLoad>
              <class>Mockery</class>
          </autoLoad>
      </php>
      
  2. Basic Mocking:
    • Replace DatabaseMigrations with DBMock in test setup:
      use Mpyw\DatabaseMock\DBMock;
      
      public function setUp(): void
      {
          parent::setUp();
          DBMock::mockPdo(); // Global mock
      }
      
  3. Query Mocking:
    • Define expectations before executing queries:
      $pdo = DBMock::mockPdo();
      $pdo->shouldSelect('SELECT * FROM users WHERE id = ?', [1])
          ->shouldFetchAllReturns([['id' => 1, 'name' => 'John']]);
      
  4. Advanced Use Cases:
    • Mock transactions, errors, or read replicas as needed:
      $pdos = DBMock::mockEachPdo();
      $pdos->writer()->shouldInsert('...')->andReturn(1);
      
  5. Validation:
    • Run existing test suites to identify mocking gaps.
    • Gradually expand coverage to complex queries.

Operational Impact

Maintenance

  • Test Reliability:
    • Pros:
      • Eliminates database flakiness (e.g., schema changes, network issues).
      • Deterministic test execution (no random failures from DB state).
    • Cons:
      • Mock drift: Tests break if real queries change but mocks aren’t updated.
      • Debugging complexity: Harder to trace issues to real database behavior.
  • Dependency Updates:
    • Alpha dependency risk: mockery-pdo may change API without notice.
    • Laravel upgrades: May require revalidation if connection abstraction changes.
  • Long-Term Costs:
    • Maintaining mocks for hundreds of queries could become time-consuming.
    • Knowledge silos: Mockery expertise may become bottlenecked to a few team members.

Support

  • Community Support:
    • Limited: 6 stars, 0 dependents, and no active maintainer engagement beyond the author.
    • Primary channels: GitHub Issues/Discussions (response time unknown).
  • Documentation:
    • Basic examples provided, but lack of depth for edge cases (e.g., raw SQL, events).
    • No migration guide for existing test suites.
  • Enterprise Considerations:
    • No SLAs or commercial support; riskier for regulated industries (e.g., finance, healthcare).

Scaling

  • Test Suite Growth:
    • Pros:
      • Faster execution (no DB setup/teardown).
      • Reduced CI costs (no database provisioning).
    • Cons:
      • Mock complexity scales with query complexity (e.g., nested queries, joins).
      • Team ramp-up: Requires Mockery training for junior devs.
  • Performance:
    • Mocking overhead is negligible for most tests but could slow down highly dynamic queries.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
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