|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace hidev\tests\unit\exception; |
| 6 | + |
| 7 | +use hidev\tests\unit\exception\stub\TestException; |
| 8 | +use PHPUnit\Framework\TestCase; |
| 9 | + |
| 10 | +class HasContextTest extends TestCase |
| 11 | +{ |
| 12 | + public function testAddContext(): void |
| 13 | + { |
| 14 | + $e = new TestException('Error'); |
| 15 | + |
| 16 | + $e->addContext(['a' => 1]); |
| 17 | + $e->addContext(['b' => 2]); |
| 18 | + |
| 19 | + $this->assertSame(['a' => 1, 'b' => 2], $e->getContext()); |
| 20 | + } |
| 21 | + |
| 22 | + public function testGetContext(): void |
| 23 | + { |
| 24 | + $e = new TestException('Error'); |
| 25 | + $e->addContext(['foo' => 'bar']); |
| 26 | + |
| 27 | + $this->assertSame(['foo' => 'bar'], $e->getContext()); |
| 28 | + } |
| 29 | + |
| 30 | + public function testMakeCreatesInstanceWithContext(): void |
| 31 | + { |
| 32 | + $e = TestException::make('Something happened', ['key' => 'value']); |
| 33 | + |
| 34 | + $this->assertInstanceOf(TestException::class, $e); |
| 35 | + $this->assertSame('Something happened', $e->getMessage()); |
| 36 | + $this->assertSame(['key' => 'value'], $e->getContext()); |
| 37 | + } |
| 38 | + |
| 39 | + public function testGetContextValueReturnsNestedValue(): void |
| 40 | + { |
| 41 | + $e = new TestException('Error'); |
| 42 | + $e->addContext([ |
| 43 | + 'user' => [ |
| 44 | + 'id' => 15, |
| 45 | + 'profile' => [ |
| 46 | + 'email' => 'test@example.com', |
| 47 | + ], |
| 48 | + ], |
| 49 | + ]); |
| 50 | + |
| 51 | + $this->assertSame(15, $e->getContextValue('user.id')); |
| 52 | + $this->assertSame('test@example.com', $e->getContextValue('user.profile.email')); |
| 53 | + } |
| 54 | + |
| 55 | + public function testGetContextValueReturnsDefaultWhenMissing(): void |
| 56 | + { |
| 57 | + $e = new TestException('Error'); |
| 58 | + $e->addContext(['foo' => 'bar']); |
| 59 | + |
| 60 | + $this->assertSame('', $e->getContextValue('missing.key')); |
| 61 | + } |
| 62 | +} |
0 commit comments