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 |
||
| 16 | class JsonApiControllerTest extends LaravelTestCase |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * Setup DB before each test. |
||
| 20 | */ |
||
| 21 | public function setUp() |
||
| 25 | |||
| 26 | /** |
||
| 27 | * This is required for \Symfony\Bridge\PsrHttpMessage\Factory to work. |
||
| 28 | * This comes as a trade-off of building the underlying package as framework-agnostic. |
||
| 29 | * |
||
| 30 | * @param string $method |
||
| 31 | * @param string $server |
||
| 32 | * @param string $uri |
||
| 33 | */ |
||
| 34 | protected function serverEnvironment($method, $server, $uri) |
||
| 40 | |||
| 41 | public function testListAction() |
||
| 42 | { |
||
| 43 | $this->serverEnvironment('GET', 'example.com', '/api/v1/employees'); |
||
| 44 | $response = $this->call('GET', 'http://example.com/api/v1/employees'); |
||
| 45 | |||
| 46 | $this->assertEquals(200, $response->getStatusCode()); |
||
| 47 | } |
||
| 48 | |||
| 49 | View Code Duplication | public function testGetActionWhenEmployeeDoesNotExist() |
|
| 50 | { |
||
| 51 | $this->serverEnvironment('GET', 'example.com', '/api/v1/employees/1000'); |
||
| 52 | $response = $this->call('GET', 'http://example.com/api/v1/employees/1000'); |
||
| 53 | |||
| 54 | $this->assertEquals(404, $response->getStatusCode()); |
||
| 55 | } |
||
| 56 | |||
| 57 | public function testPostAction() |
||
| 60 | |||
| 61 | public function testPatchAction() |
||
| 64 | |||
| 65 | public function testPutAction() |
||
| 68 | |||
| 69 | View Code Duplication | public function testDeleteActionWhenEmployeeDoesNotExistReturns404() |
|
| 70 | { |
||
| 76 | } |
||
| 77 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: