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

Symfony Test Utils Laravel Package

redhotmagma/symfony-test-utils

Utilities to simplify testing in Symfony projects. Provides helpers and small tools for common test setup tasks, assertions, and fixtures to reduce boilerplate and speed up writing reliable unit and integration tests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package to your Laravel project via Composer:

    composer require redhotmagma/symfony-test-utils --dev
    

    Since Laravel uses Symfony components under the hood, this package integrates seamlessly.

  2. First Use Case: Mocking Symfony Components Use the SymfonyTestUtils facade to mock Symfony services (e.g., ContainerInterface, HttpClientInterface) in tests:

    use RedHotMagma\SymfonyTestUtils\Facades\SymfonyTestUtils;
    
    $mockContainer = SymfonyTestUtils::mockContainer([
        'some.service' => $this->createMock(SomeService::class),
    ]);
    
  3. Where to Look First

    • Facade: RedHotMagma\SymfonyTestUtils\Facades\SymfonyTestUtils
    • Documentation: Check the GitLab repo for usage examples.
    • Test Helpers: Focus on mockContainer(), mockHttpClient(), and createTestRequest() for common needs.

Implementation Patterns

Common Workflows

  1. Mocking the Symfony Container Replace Laravel’s Container with a mock for isolated testing:

    $mockContainer = SymfonyTestUtils::mockContainer([
        'mailer' => $this->createMock(MailerInterface::class),
    ]);
    $this->app->instance(ContainerInterface::class, $mockContainer);
    
  2. Testing HTTP Clients Simulate API calls without hitting external services:

    $mockClient = SymfonyTestUtils::mockHttpClient([
        'GET /api/users' => ['status' => 200, 'body' => '{"id":1}'],
    ]);
    $this->app->instance(HttpClientInterface::class, $mockClient);
    
  3. Creating Test Requests Generate Symfony-style requests for controller testing:

    $request = SymfonyTestUtils::createTestRequest('POST', '/login', [
        'email' => '[email protected]',
    ]);
    $response = $this->app->handle($request);
    
  4. Integration with Laravel’s Testing Combine with Laravel’s Http and Database testing tools:

    use Illuminate\Foundation\Testing\TestCase;
    
    class UserTest extends TestCase {
        protected function setUp(): void {
            parent::setUp();
            $this->mockContainer(['auth' => $this->createMock(Auth::class)]);
        }
    }
    

Best Practices

  • Isolation: Use mocks to test components in isolation (e.g., services, repositories).
  • Realism: For integration tests, partially mock dependencies (e.g., mock HttpClient but use real Database).
  • Cleanup: Reset mocks between tests to avoid state pollution.

Gotchas and Tips

Pitfalls

  1. Laravel-Specific Quirks

    • The package targets Symfony, so some Laravel-specific services (e.g., Illuminate\Auth\AuthManager) may need manual mocking.
    • Example: Mock Auth via Laravel’s createMock(AuthManager::class) instead of Symfony’s UserProviderInterface.
  2. Container Binding Conflicts

    • Overriding the container may break Laravel’s service providers. Use instance() sparingly or wrap in refresh():
      $this->app->refresh();
      $this->app->instance(ContainerInterface::class, $mockContainer);
      
  3. HttpClient Mocking Limitations

    • The mock only handles predefined routes. Unmapped routes will throw exceptions. Use wildcards (*) for dynamic paths:
      $mockClient = SymfonyTestUtils::mockHttpClient([
          'GET /api/*' => ['status' => 200],
      ]);
      

Debugging Tips

  • Verify Mocks: Use assertInstanceOf() to confirm mocks are injected:
    $this->assertInstanceOf(MockObject::class, $this->app->make('some.service'));
    
  • Log Mock Calls: Enable PHPUnit’s mock logging:
    $this->getMockBuilder(SomeService::class)
         ->disableOriginalConstructor()
         ->setMethods(['someMethod'])
         ->getMock()
         ->expects($this->once())
         ->method('someMethod')
         ->will($this->returnValue(true));
    
  • Check for Deprecated Methods: The package may use Symfony’s HttpClient methods that differ from Laravel’s Http facade.

Extension Points

  1. Custom Mock Factories Extend the package by creating your own mock factory:
    use RedHotMagma\SymfonyTestUtils\MockFactory;
    
    class CustomMockFactory extends MockFactory {
        public function mockCustomService(array $methods = []) {
            return $this->createMock(CustomService::class, $methods);
        }
    }
    
  2. Middleware Testing Combine with Laravel’s Middleware testing:
    $request = SymfonyTestUtils::createTestRequest('GET', '/');
    $response = $this->app->handle($request);
    $this->assertEquals(200, $response->getStatusCode());
    
  3. Event Dispatcher Mocks Mock Symfony’s EventDispatcherInterface for testing event listeners:
    $mockDispatcher = SymfonyTestUtils::mockEventDispatcher();
    $this->app->instance(EventDispatcherInterface::class, $mockDispatcher);
    
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.
thuraaung2493/laravel-rulecraft
cyberwizard/schedule-catchup
livetennisapi/livetennisapi-laravel
roundly-consulting/notifications-for-laravel
flightsadmin/bootstrap-starter-kit
lasserafn/laravel-intempus
likyly/sdk
tdt/input
coreation/php-shapefile
coreation/gisconverter
primix/widgets
primix/notifications
primix/actions
primix/tables
primix/details
primix/forms
primix/support
marcelgwerder/laravel-api-handler
firebrikdotcom/conveyor-laravel-broadcaster
kanata-php/conveyor-laravel-broadcaster