Weave 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

Test Double Bundle Laravel Package

docteurklein/test-double-bundle

Symfony bundle to simplify creating test doubles. Replace services automatically with stubs or fakes via DI container tags, improving test isolation and speed (e.g., Behat). Access original implementations with .real for infrastructure tests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require docteurklein/test-double-bundle --dev
    

    Add the bundle only in test environments (e.g., config/bundles.php):

    TestDoubleBundle\TestDoubleBundle::class => ['test' => true],
    
  2. First Use Case: Replace a service (e.g., GithubClient) with a stub for isolated testing. Tag the service in its definition (e.g., src/Service/GuzzleClient.php):

    use Doctrine\Common\Annotations\Tag;
    
    /**
     * @Service("github_client")
     * @Tag("test_double", attributes={"stub"="GithubClient"})
     */
    class GuzzleClient implements GithubClient { ... }
    
  3. Access the Stub: Inject the prophecy service in your test context (e.g., Behat):

    $this->getContainer()->get('github_client.prophecy')->method()->willReturn($mockValue);
    

Implementation Patterns

Workflows

  1. Stubbing Services:

    • Use @Tag("test_double", attributes={"stub"="InterfaceName"}) to auto-generate a Prophecy stub.
    • Access the prophecy via <service_id>.prophecy (e.g., github_client.prophecy).
    • Example: Mock HTTP responses in Behat:
      $this->container->get('http_client.prophecy')
          ->get('/api/issues')->willReturn(new Response(200, [], '{}'));
      
  2. Faking Services:

    • Replace a service with a custom implementation using @Tag("test_double", attributes={"fake"="service.fake"}).
    • Define the fake service with the same interface (e.g., FakeGithubClient).
    • Example:
      // Fake service definition
      $container->set('github_client.fake', FakeGithubClient::class);
      
  3. Integration with Behat:

    • Inject the container into Behat contexts to manipulate stubs/fakes dynamically.
    • Use stub.prophet->checkPredictions() to verify interactions post-test.

Key Patterns

  • Isolation: Stub repositories to avoid database dependencies in unit/integration tests.
  • Hybrid Testing: Use .real suffix (e.g., github_client.real) for infrastructure tests.
  • Context-Specific Fixtures: Configure stubs per scenario (e.g., Behat step definitions).

Gotchas and Tips

Pitfalls

  1. Final Classes: Stubbing fails if the original service is final (Prophecy limitation).

    • Workaround: Use fakes instead or refactor to avoid final.
  2. Service Overrides:

    • Ensure the original service isn’t manually overridden in tests (conflicts with bundle logic).
    • Debug Tip: Check container.has('github_client.real') to verify original services exist.
  3. Prophecy Leaks:

    • Unchecked prophecies cause silent failures. Always call checkPredictions().
    • Tip: Wrap assertions in a try-catch to fail fast:
      try {
          $this->container->get('stub.prophet')->checkPredictions();
      } catch (\Prophecy\Exception\Exception $e) {
          throw new \RuntimeException('Stub verification failed: ' . $e->getMessage());
      }
      

Tips

  1. Tag Attributes:

    • Omit stub/fake attributes to auto-generate stubs for the service’s class.
    • Example: @Tag("test_double") → stubs GuzzleClient if the service implements GithubClient.
  2. Performance:

    • Stubbing reduces test suite time by avoiding DB resets. Profile with/without the bundle.
  3. Extension Points:

    • Customize stub behavior by extending DocteurKlein\TestDoubleBundle\DependencyInjection\Compiler\TestDoublePass.
    • Example: Add default return values via a compiler pass.
  4. Debugging:

    • Dump the container to inspect stubs/fakes:
      $this->container->get('debug:container')->dump();
      
    • Look for .stub/.fake/.prophecy services.
  5. Legacy Code:

    • For non-interface services, use fakes to avoid breaking changes during migration.
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.
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource