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 |
||
| 21 | class TimedGeocoderTest extends TestCase |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * @var Stopwatch |
||
| 25 | */ |
||
| 26 | private $stopwatch; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * @var Provider |
||
| 30 | */ |
||
| 31 | private $delegate; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @var TimedGeocoder |
||
| 35 | */ |
||
| 36 | private $geocoder; |
||
| 37 | |||
| 38 | protected function setUp() |
||
| 39 | { |
||
| 40 | $this->stopwatch = new Stopwatch(); |
||
| 41 | $this->delegate = $this->getMockBuilder(Provider::class)->getMock(); |
||
| 42 | $this->geocoder = new TimedGeocoder($this->delegate, $this->stopwatch); |
||
| 43 | } |
||
| 44 | |||
| 45 | public function testGeocode() |
||
| 46 | { |
||
| 47 | $this->delegate->expects($this->once()) |
||
| 48 | ->method('geocodeQuery') |
||
| 49 | ->will($this->returnValue(new AddressCollection([]))); |
||
| 50 | |||
| 51 | $this->geocoder->geocode('foo'); |
||
| 52 | |||
| 53 | $this->assertCount(1, $this->stopwatch->getSectionEvents('__root__')); |
||
| 54 | } |
||
| 55 | |||
| 56 | public function testGeocodeThrowsException() |
||
| 57 | { |
||
| 58 | $this->delegate->expects($this->once()) |
||
| 59 | ->method('geocodeQuery') |
||
| 60 | ->will($this->throwException($exception = new \Exception())); |
||
| 61 | |||
| 62 | try { |
||
| 63 | $this->geocoder->geocode('foo'); |
||
| 64 | $this->fail('Geocoder::geocode should throw an exception'); |
||
| 65 | } catch (\Exception $e) { |
||
| 66 | $this->assertSame($exception, $e); |
||
| 67 | } |
||
| 68 | |||
| 69 | $this->assertCount(1, $this->stopwatch->getSectionEvents('__root__')); |
||
| 70 | } |
||
| 71 | |||
| 72 | public function testReverse() |
||
| 73 | { |
||
| 74 | $this->delegate->expects($this->once()) |
||
| 75 | ->method('reverseQuery') |
||
| 76 | ->will($this->returnValue(new AddressCollection([]))); |
||
| 77 | |||
| 78 | $this->geocoder->reverse(0, 0); |
||
| 79 | |||
| 80 | $this->assertCount(1, $this->stopwatch->getSectionEvents('__root__')); |
||
| 81 | } |
||
| 82 | |||
| 83 | public function testReverseThrowsException() |
||
| 84 | { |
||
| 85 | $this->delegate->expects($this->once()) |
||
| 86 | ->method('reverseQuery') |
||
| 87 | ->will($this->throwException($exception = new \Exception())); |
||
| 88 | |||
| 89 | try { |
||
| 90 | $this->geocoder->reverse(0, 0); |
||
| 91 | $this->fail('Geocoder::reverse should throw an exception'); |
||
| 92 | } catch (\Exception $e) { |
||
| 93 | $this->assertSame($exception, $e); |
||
| 94 | } |
||
| 95 | |||
| 96 | $this->assertCount(1, $this->stopwatch->getSectionEvents('__root__')); |
||
| 97 | } |
||
| 98 | } |
||
| 99 |