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 |
||
11 | class ModelHydratorTest extends TestCase |
||
12 | { |
||
13 | private $hydrator; |
||
14 | private $model; |
||
15 | |||
16 | public function setUp() |
||
17 | { |
||
18 | $this->hydrator = new ModelHydrator(); |
||
19 | $this->model = m::mock('alias:'.CreateableFromArray::class); |
||
20 | } |
||
21 | |||
22 | public function testSuccessfulHydration() |
||
23 | { |
||
24 | $response = m::mock( |
||
25 | Response::class, |
||
26 | [ |
||
27 | 200, |
||
28 | ['Content-Type' => 'application/json'], |
||
29 | '{"document_tone": {}}' |
||
30 | ] |
||
31 | ); |
||
32 | |||
33 | $response->makePartial(); |
||
34 | |||
35 | $this->model->shouldReceive('createFromArray')->andReturn(['document_tone' => []]); |
||
36 | |||
37 | $result = $this->hydrator->hydrate($response, $this->model); |
||
38 | |||
39 | $this->assertInstanceOf(CreateableFromArray::class, $result); |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * @expectedException \IBM\Watson\Common\Exception\HydrationException |
||
44 | * @expectedExceptionMessage The ModelHydrator requires a model class as the second parameter |
||
45 | */ |
||
46 | public function testHydrateFailsWithoutClass() |
||
47 | { |
||
48 | $response = m::mock(Response::class, [200]); |
||
49 | |||
50 | $this->hydrator->hydrate($response); |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @expectedException \IBM\Watson\Common\Exception\HydrationException |
||
55 | * @expectedExceptionMessage The ModelHydrator cannot hydrate response with Content-Type: text/plain |
||
56 | */ |
||
57 | public function testHydrateFailsForNoneJsonResponses() |
||
58 | { |
||
59 | $response = m::mock(Response::class, [200, ['Content-Type' => 'text/plain']])->makePartial(); |
||
60 | |||
61 | $this->hydrator->hydrate($response, \stdClass::class); |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * @expectedException \IBM\Watson\Common\Exception\HydrationException |
||
66 | */ |
||
67 | public function testHydrateFailsWhenJsonDecodeFails() |
||
68 | { |
||
69 | $response = m::mock(Response::class, [200, ['Content-Type' => 'application/json'], '{"brokenJson}']) |
||
70 | ->makePartial(); |
||
71 | |||
72 | $this->hydrator->hydrate($response, \stdClass::class); |
||
73 | } |
||
74 | } |
||
75 |