phplaravelmockingphpunitsentry

How to "mock" Sentry client in the PHPUnit tests


In case if you need to test PHP application error handlers, you have to "mock" or just disable sending errors on remote servers in the Sentry client. What is the right way to do this?


Solution

  • This is the example for Laravel, but this approach should work for any framework.

    use Sentry\Client;
    use Sentry\EventFactory;
    use Sentry\Options;
    use Sentry\Serializer\RepresentationSerializer;
    use Sentry\Serializer\Serializer;
    use Sentry\Transport\NullTransport;
    
    private function mockSentry(): void
    {
        /** @var \Sentry\State\Hub $sentry */
        $sentry = $this->app['sentry']; // Get sentry object from Laravel's container
    
        $client = new Client(
            new Options(),
            new NullTransport(),
            new EventFactory(
                new Serializer(new Options()),
                new RepresentationSerializer(new Options()),
                new Options(),
                '1',
                '1',
            ),
        );
        $sentry->bindClient($client);
    }