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 |
||
15 | class LocatorTest extends \PHPUnit_Framework_TestCase |
||
16 | { |
||
17 | public function testConstructShouldSettersDecoder() |
||
18 | { |
||
19 | $credentials = $this->createMock(Credentials::class); |
||
20 | $client = $this->createMock(Client::class); |
||
21 | $decoder = $this->createMock(Decoder::class); |
||
22 | |||
23 | $locator = new Locator($credentials, $client, $decoder); |
||
24 | |||
25 | $this->assertInstanceOf(NotificationService::class, $locator); |
||
26 | $this->assertInstanceOf(SearchService::class, $locator); |
||
27 | $this->assertInstanceOf(Service::class, $locator); |
||
28 | $this->assertAttributeSame($decoder, 'decoder', $locator); |
||
29 | } |
||
30 | |||
31 | public function testGetByCodeShouldDoAGetRequestAddingCredentialsData() |
||
32 | { |
||
33 | $credentials = $this->createMock(Credentials::class); |
||
34 | $client = $this->createMock(CLient::class); |
||
35 | $decoder = $this->createMock(Decoder::class); |
||
36 | |||
37 | $locator = new Locator($credentials, $client, $decoder); |
||
38 | |||
39 | $wsUrl = 'https://ws.test.com/v2/transactions?token=zzzzz'; |
||
40 | |||
41 | $credentials->expects($this->once()) |
||
42 | ->method('getWsUrl') |
||
43 | ->with('/v2/pre-approvals/123456', []) |
||
44 | ->willReturn($wsUrl); |
||
45 | |||
46 | $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><transaction/>'); |
||
47 | $client->expects($this->once())->method('get')->with($wsUrl)->willReturn($xml); |
||
48 | |||
49 | $transaction = $this->createMock(Transaction::class); |
||
50 | $decoder->expects($this->once())->method('decode')->with($xml)->willReturn($transaction); |
||
51 | |||
52 | $this->assertEquals($transaction, $locator->getByCode('123456')); |
||
53 | } |
||
54 | |||
55 | public function testGetByNotificationShouldDoAGetRequestAddingCredentialsData() |
||
56 | { |
||
57 | $credentials = $this->createMock(Credentials::class); |
||
58 | $client = $this->createMock(Client::class); |
||
59 | $decoder = $this->createMock(Decoder::class); |
||
60 | |||
61 | $locator = new Locator($credentials, $client, $decoder); |
||
62 | |||
63 | $wsUrl = 'https://ws.test.com/v2/transactions?token=xxxxx'; |
||
64 | $credentials->expects($this->once()) |
||
65 | ->method('getWsUrl') |
||
66 | ->with('/v2/pre-approvals/notifications/abcd', []) |
||
67 | ->willReturn($wsUrl); |
||
68 | |||
69 | $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><transaction/>'); |
||
70 | $client->expects($this->once())->method('get')->with($wsUrl)->willReturn($xml); |
||
71 | |||
72 | $transaction = $this->createMock(Transaction::class); |
||
73 | |||
74 | $decoder->expects($this->once()) |
||
82 |