-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContainerTest.php
113 lines (98 loc) · 3.38 KB
/
ContainerTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
declare(strict_types = 1);
namespace Tests\Innmind\DI;
use Innmind\DI\{
Builder,
Container,
Exception\ServiceNotFound,
Exception\CircularDependency,
};
use Innmind\BlackBox\{
PHPUnit\BlackBox,
PHPUnit\Framework\TestCase,
Set,
};
use Fixtures\Innmind\DI\Services;
class ContainerTest extends TestCase
{
use BlackBox;
public function testInterface()
{
$this->assertInstanceOf(Container::class, Builder::new()->build());
}
public function testConstructingTheDefinitionsIsImmutable()
{
$this
->forAll(Set\Unicode::strings())
->then(function($name) {
$container = Builder::new();
$container2 = $container->add($name, static fn() => new \stdClass);
$this->assertInstanceOf(Builder::class, $container2);
$this->assertNotSame($container2, $container);
$this->assertInstanceOf(\stdClass::class, $container2->build()($name));
try {
$container->build()($name);
$this->fail('it should throw');
} catch (\Exception $e) {
$this->assertInstanceOf(ServiceNotFound::class, $e);
$this->assertSame($name, $e->getMessage());
}
});
}
public function testServiceIsOnlyBuiltOnce()
{
$this
->forAll(Set\Unicode::strings())
->then(function($name) {
$container = Builder::new()
->add($name, static fn() => new \stdClass)
->build();
$this->assertSame($container($name), $container($name));
});
}
public function testDependenciesCanBeAccesedWhenBuildingService()
{
$this
->forAll(
Set\Unicode::strings(),
Set\Unicode::strings(),
)
->filter(static fn($a, $b) => $a !== $b)
->then(function($name, $dependency) {
$container = Builder::new()
->add($name, static fn($get) => $get($dependency))
->add($dependency, static fn() => new \stdClass)
->build();
$this->assertSame($container($dependency), $container($name));
});
}
public function testCircularDependenciesAreIntercepted()
{
$this
->forAll(
Set\Unicode::strings(),
Set\Unicode::strings(),
)
->filter(static fn($a, $b) => $a !== $b)
->then(function($name, $dependency) {
$container = Builder::new()
->add($name, static fn($get) => $get($dependency))
->add($dependency, static fn($get) => $get($name))
->build();
try {
$container($name);
$this->fail('it should throw');
} catch (CircularDependency $e) {
$this->assertSame("$name > $dependency > $name", $e->getMessage());
}
});
}
public function testEnumCaseCanBeUsedToReferenceAService()
{
$expected = new \stdClass;
$container = Builder::new()
->add(Services::a, static fn() => $expected)
->build();
$this->assertSame($expected, $container(Services::a));
}
}