|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Lcobucci\ErrorHandling\Tests; |
| 5 | + |
| 6 | +use Lcobucci\ErrorHandling\ErrorLoggingMiddleware; |
| 7 | +use PHPUnit\Framework\MockObject\MockObject; |
| 8 | +use PHPUnit\Framework\TestCase; |
| 9 | +use Psr\Http\Server\RequestHandlerInterface; |
| 10 | +use Psr\Log\LoggerInterface; |
| 11 | +use RuntimeException; |
| 12 | +use Zend\Diactoros\Response; |
| 13 | +use Zend\Diactoros\ServerRequest; |
| 14 | + |
| 15 | +/** |
| 16 | + * @coversDefaultClass \Lcobucci\ErrorHandling\ErrorLoggingMiddleware |
| 17 | + */ |
| 18 | +final class ErrorLoggingMiddlewareTest extends TestCase |
| 19 | +{ |
| 20 | + /** |
| 21 | + * @var LoggerInterface&MockObject |
| 22 | + */ |
| 23 | + private $logger; |
| 24 | + |
| 25 | + /** |
| 26 | + * @before |
| 27 | + */ |
| 28 | + public function createLogger(): void |
| 29 | + { |
| 30 | + $this->logger = $this->createMock(LoggerInterface::class); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @test |
| 35 | + * |
| 36 | + * @covers ::__construct |
| 37 | + * @covers ::process |
| 38 | + */ |
| 39 | + public function processShouldLogAllExceptionsOrErrorsThatHappenedDuringRequestHandling(): void |
| 40 | + { |
| 41 | + $error = new RuntimeException('Testing'); |
| 42 | + |
| 43 | + $this->logger->expects(self::once()) |
| 44 | + ->method('debug') |
| 45 | + ->with('Error happened while processing request', ['exception' => $error]); |
| 46 | + |
| 47 | + $handler = $this->createMock(RequestHandlerInterface::class); |
| 48 | + $handler->method('handle')->willThrowException($error); |
| 49 | + |
| 50 | + $middleware = new ErrorLoggingMiddleware($this->logger); |
| 51 | + |
| 52 | + $this->expectExceptionObject($error); |
| 53 | + $middleware->process(new ServerRequest(), $handler); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * @test |
| 58 | + * |
| 59 | + * @covers ::__construct |
| 60 | + * @covers ::process |
| 61 | + */ |
| 62 | + public function processShouldReturnResponseWhenEverythingIsAlright(): void |
| 63 | + { |
| 64 | + $this->logger->expects(self::never())->method('debug'); |
| 65 | + |
| 66 | + $response = new Response(); |
| 67 | + |
| 68 | + $handler = $this->createMock(RequestHandlerInterface::class); |
| 69 | + $handler->method('handle')->willReturn($response); |
| 70 | + |
| 71 | + $middleware = new ErrorLoggingMiddleware($this->logger); |
| 72 | + |
| 73 | + self::assertSame($response, $middleware->process(new ServerRequest(), $handler)); |
| 74 | + } |
| 75 | +} |
0 commit comments