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

Prophecy Phpunit Laravel Package

console-helpers/prophecy-phpunit

PHPUnit integration helpers for Prophecy, providing convenience traits and utilities to streamline mock creation, prophecy assertions, and cleanup in your test suite. Designed to reduce boilerplate and keep Prophecy-based unit tests tidy and consistent.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require --dev console-helpers/prophecy-phpunit
    

    No additional configuration is required—it integrates seamlessly with PHPUnit and Prophecy.

  2. First Use Case Replace PHPUnit’s native mocking with Prophecy in a test:

    use ConsoleHelpers\Prophecy\ProphecyTestCase;
    
    class ExampleTest extends ProphecyTestCase
    {
        public function testMockingWithProphecy()
        {
            $mock = $this->prophesize('App\Services\ExampleService');
            $mock->doSomething()->willReturn('mocked result');
    
            $result = $mock->reveal()->doSomething();
            $this->assertEquals('mocked result', $result);
        }
    }
    
  3. Key Files to Explore

    • ProphecyTestCase.php: Core test case class extending PHPUnit’s TestCase.
    • Prophecy’s official documentation for advanced usage.

Implementation Patterns

Workflow Integration

  1. Test Case Inheritance Extend ProphecyTestCase instead of PHPUnit’s base TestCase:

    class UserServiceTest extends ProphecyTestCase { ... }
    
    • Automatically loads Prophecy’s prophesize() method.
  2. Mocking Dependencies Replace manual mocks with Prophecy’s fluent syntax:

    $repository = $this->prophesize('App\Repositories\UserRepository');
    $repository->find(1)->willReturn((new User())->setName('Test User'));
    
  3. Partial Mocks Use partialMock() for existing objects (if needed, though Prophecy discourages this):

    $service = $this->partialMock('App\Services\RealService', ['log']);
    
  4. Laravel-Specific Patterns

    • Service Container Mocking:
      $this->app->instance('App\Contracts\UserRepository', $this->prophesize('App\Repositories\UserRepository')->reveal());
      
    • Event Dispatcher Mocking:
      $events = $this->prophesize('Illuminate\Events\Dispatcher');
      $this->app->instance('events', $events->reveal());
      
  5. Assertion Helpers Combine with PHPUnit assertions:

    $mock->methodWasCalled('save');
    $this->assertTrue($mock->methodWasCalled('save'));
    

Gotchas and Tips

Pitfalls

  1. reveal() Timing

    • Issue: Forgetting to call reveal() before invoking methods on a prophecy.
      $mock->doSomething(); // Fails: Prophecy object not revealed.
      
    • Fix: Always reveal before interaction:
      $mock->reveal()->doSomething();
      
  2. Double Invocation

    • Issue: Prophecy throws Prophecy\Exception\DoubleInvocationException if a method is called more times than defined.
      $mock->save()->willReturn(true); // Only allows 1 call.
      $mock->save(); // OK
      $mock->save(); // Throws exception.
      
    • Fix: Use willReturnOnConsecutiveCalls() or willReturnCallback().
  3. Laravel Facade Mocking

    • Issue: Directly mocking Laravel facades (e.g., Auth::shouldReceive()) may not work as expected.
    • Fix: Bind the facade’s underlying instance to a prophecy:
      $this->app->instance('auth', $this->prophesize('Illuminate\Auth\AuthManager')->reveal());
      
  4. Static Method Mocking

    • Issue: Prophecy cannot mock static methods natively.
    • Workaround: Use partialMock() or a wrapper class.

Debugging Tips

  1. Enable Prophecy Debugging Set the PROPHECY_DEBUG environment variable to 1 for detailed error messages:

    PROPHECY_DEBUG=1 phpunit
    
  2. Inspect Prophecies Use getProphecy() to debug interactions:

    $prophecy = $mock->getProphecy();
    $prophecy->checkPredictions(); // Verify all expectations were met.
    
  3. Laravel’s Service Provider Mocking

    • Tip: For testing service providers, bind prophecies in setUp():
      public function setUp(): void
      {
          parent::setUp();
          $this->app->instance('App\Contracts\ExampleContract', $this->prophesize('App\Services\ExampleService')->reveal());
      }
      

Extension Points

  1. Custom Prophecy Classes Extend ProphecyTestCase to add domain-specific helpers:

    class ApiTestCase extends ProphecyTestCase
    {
        protected function createMockApiClient(): \GuzzleHttp\Client
        {
            return $this->prophesize('GuzzleHttp\Client')->reveal();
        }
    }
    
  2. Trait for Shared Mocks Use traits to avoid repetition:

    trait MocksUsers
    {
        protected function createMockUserRepository(): \App\Repositories\UserRepository
        {
            return $this->prophesize('App\Repositories\UserRepository')->reveal();
        }
    }
    
  3. Integration with Laravel’s MockApplication Combine with Laravel’s testing tools for deeper integration:

    use Illuminate\Foundation\Testing\Concerns\InteractsWithContainer;
    
    class ServiceTest extends ProphecyTestCase
    {
        use InteractsWithContainer;
        // ...
    }
    
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