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

Testing Bundle Laravel Package

dosfarma/testing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require dosfarma/testing-bundle
    

    Register the bundle in config/bundles.php (Symfony):

    return [
        // ...
        Dosfarma\TestingBundle\DosfarmaTestingBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Mocking HTTP Requests Use the Dosfarma\TestingBundle\TestCase\WebTestCase base class to mock HTTP requests in Laravel-style tests:

    use Dosfarma\TestingBundle\TestCase\WebTestCase;
    
    class ExampleTest extends WebTestCase
    {
        public function testMockedRequest()
        {
            $this->mockHttpRequest('GET', '/api/users', [
                'status' => 200,
                'response' => ['data' => ['id' => 1, 'name' => 'John']],
            ]);
    
            $response = $this->get('/api/users');
            $this->assertJson(['data' => ['id' => 1, 'name' => 'John']]);
        }
    }
    
  3. Key Entry Points

    • mockHttpRequest(): Simulate HTTP responses (GET/POST/PUT/DELETE).
    • mockService(): Stub external services (e.g., queues, APIs).
    • assertDatabaseHas(): Custom assertions for database state (if extended).

Implementation Patterns

Workflow: API Contract Testing

  1. Define Mocks in Tests Use mockHttpRequest() to simulate upstream/downstream API calls:

    $this->mockHttpRequest('POST', 'https://payment-gateway.com/charge', [
        'status' => 200,
        'response' => ['transaction_id' => 'abc123'],
    ]);
    
  2. Integrate with Laravel HTTP Clients Combine with Laravel’s Http facade for seamless testing:

    $response = Http::post('https://payment-gateway.com/charge');
    $this->assertEquals('abc123', $response['transaction_id']);
    
  3. Service Layer Stubbing Mock services (e.g., PaymentService) in unit tests:

    $this->mockService(PaymentService::class, function ($method, $args) {
        return ['success' => true];
    });
    

Patterns for Reusability

  • Test Traits: Extract mock configurations into traits for DRY tests:
    trait MocksPaymentGateway
    {
        protected function mockGateway()
        {
            $this->mockHttpRequest('POST', 'https://payment-gateway.com/charge', [...]);
        }
    }
    
  • Fixtures: Use mockHttpRequest() to load test data dynamically (e.g., mocking a CMS API for content tests).

Gotchas and Tips

Pitfalls

  1. Namespace Collisions The bundle uses Dosfarma\TestingBundle—ensure no naming conflicts with other dosfarma/* packages.

  2. Laravel-Specific Quirks

    • HTTP Client: The bundle assumes Symfony’s HttpClient; wrap Laravel’s Http in a Symfony-compatible layer if needed:
      use Symfony\Component\HttpClient\HttpClient;
      $client = HttpClient::create(['base_uri' => 'https://api.example.com']);
      
    • Assertions: Custom assertions (e.g., assertDatabaseHas) may not work out-of-the-box; extend the base test case:
      class CustomTestCase extends WebTestCase
      {
          protected function assertDatabaseHasTable($table, $data)
          {
              // Custom logic
          }
      }
      
  3. Mock Persistence Mocks reset between tests unless explicitly configured. Use beforeEach() to reapply mocks:

    public function beforeEach(): void
    {
        $this->mockHttpRequest('GET', '/api/users', [...]);
    }
    

Debugging Tips

  • Verify Mocks: Use getMockedRequests() to inspect active mocks:
    $this->getMockedRequests(); // Returns array of mocked endpoints
    
  • Log Mock Calls: Extend the bundle to log mock invocations for debugging:
    $this->mockService(MyService::class, function ($method, $args) {
        \Log::debug("Mock called: $method with args: " . json_encode($args));
        return [...];
    });
    

Extension Points

  1. Custom Mock Providers Add new mock types by extending Dosfarma\TestingBundle\Mock\MockProviderInterface:

    class QueueMockProvider implements MockProviderInterface
    {
        public function mock($queueName, callable $callback) { ... }
    }
    

    Register via the bundle’s configuration.

  2. Laravel-Specific Extensions Override the base test case to integrate with Laravel’s RefreshDatabase or MigrateFreshDatabase:

    class LaravelTestCase extends WebTestCase
    {
        use RefreshDatabase;
    
        public function setUp(): void
        {
            parent::setUp();
            // Laravel-specific setup
        }
    }
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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