Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
24 | class AliasContainerTest extends \PHPUnit_Framework_TestCase |
||
25 | { |
||
26 | /** |
||
27 | * @var \PHPUnit_Framework_MockObject_MockObject | \Interop\Container\ContainerInterface |
||
28 | */ |
||
29 | private $container; |
||
30 | /** |
||
31 | * @var AliasContainer |
||
32 | */ |
||
33 | private $obj; |
||
34 | |||
35 | protected function setUp() |
||
36 | { |
||
37 | $this->container = $this->getMockBuilder('\Interop\Container\ContainerInterface') |
||
38 | ->setMethods(['get']) |
||
39 | ->getMockForAbstractClass(); |
||
40 | |||
41 | $this->obj = new AliasContainer(); |
||
42 | |||
43 | $this->obj->setContainer($this->container); |
||
44 | } |
||
45 | |||
46 | public function testAdd() |
||
47 | { |
||
48 | $c = $this->obj; |
||
49 | |||
50 | $this->assertFalse($c->has('alias')); |
||
51 | $this->assertFalse($c->has('nonexistent')); |
||
52 | |||
53 | $c->add('alias', 'orig'); |
||
54 | |||
55 | $this->assertTrue($c->has('alias')); |
||
56 | $this->assertFalse($c->has('nonexistent')); |
||
57 | } |
||
58 | |||
59 | public function testGet() |
||
60 | { |
||
61 | $c = $this->obj; |
||
62 | |||
63 | $this->container->expects($this->once()) |
||
64 | ->method('get') |
||
65 | ->with('orig') |
||
66 | ->willReturn('orig resolved'); |
||
67 | |||
68 | $c->add('alias', 'orig'); |
||
69 | |||
70 | $this->assertSame('orig resolved', $c->get('alias')); |
||
71 | } |
||
72 | |||
73 | public function testGetWithArguments() |
||
74 | { |
||
75 | $c = $this->obj; |
||
76 | |||
77 | $this->container->expects($this->once()) |
||
78 | ->method('get') |
||
79 | ->with('orig', ['with', 'arguments']) |
||
80 | ->willReturn('orig resolved with arguments'); |
||
81 | |||
82 | $c->add('alias', 'orig'); |
||
83 | |||
84 | $this->assertSame('orig resolved with arguments', $c->get('alias', ['with', 'arguments'])); |
||
85 | } |
||
86 | |||
87 | /** |
||
88 | * @expectedException \League\Container\Exception\NotFoundException |
||
89 | * @expectedExceptionMessage Alias (nonexistent) is not registered and therefore cannot be resolved |
||
90 | */ |
||
91 | public function testGetNonexistent() |
||
92 | { |
||
93 | $c = $this->obj; |
||
94 | |||
95 | $c->get('nonexistent'); |
||
96 | } |
||
97 | } |
||
98 |