|
| 1 | +## Running and writing tests |
| 2 | +[Back to the navigation](README.md) |
| 3 | + |
| 4 | + |
| 5 | +### Run Test Suite |
| 6 | + |
| 7 | +The code is unit tested, there are also some functional tests. To run tests on |
| 8 | +your machine, from a CLI, run |
| 9 | + |
| 10 | +```bash |
| 11 | +$ composer update |
| 12 | +$ phpunit |
| 13 | +``` |
| 14 | + |
| 15 | +### Write tests |
| 16 | + |
| 17 | +It is always great if someone wants to contribute and extend the functionality of |
| 18 | +the API client. But all new features must be properly tested. To test a new API |
| 19 | +function, one should test its communication with the HTTP client. The code should |
| 20 | +never make an actual call to Github. Testing could easily be done with mocking. |
| 21 | + |
| 22 | +If you want to write test for the function that shows you comments to a gist. |
| 23 | + |
| 24 | +```php |
| 25 | +class Comments extends AbstractApi |
| 26 | +{ |
| 27 | + // ... |
| 28 | + public function show($gist, $comment) |
| 29 | + { |
| 30 | + return $this->get('/gists/'.rawurlencode($gist).'/comments/'.rawurlencode($comment)); |
| 31 | + } |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +The test will look like this: |
| 36 | + |
| 37 | +```php |
| 38 | +use Github\Tests\Api\TestCase; |
| 39 | + |
| 40 | +class CommentsTest extends TestCase |
| 41 | +{ |
| 42 | + // ... |
| 43 | + |
| 44 | + /** |
| 45 | + * @test |
| 46 | + */ |
| 47 | + public function shouldShowGistComment() |
| 48 | + { |
| 49 | + // Create a variable with the "Server response". |
| 50 | + $expectedValue = array('comment1'); |
| 51 | + |
| 52 | + // Get the API mock (see "getApiClass" below). |
| 53 | + $api = $this->getApiMock(); |
| 54 | + |
| 55 | + $api->expects($this->once()) // Expect one call |
| 56 | + ->method('get') // A GET request |
| 57 | + ->with('/gists/123/comments/456') // URI should be "/gists/123/comments/456" |
| 58 | + ->will($this->returnValue($expectedValue)); // Should return the "Server response" |
| 59 | + |
| 60 | + // Call Comments::show |
| 61 | + $result = $api->show(123, 456); |
| 62 | + |
| 63 | + // Verify that the result is the "Server response" as we expect. |
| 64 | + $this->assertEquals($expectedValue, $result); |
| 65 | + } |
| 66 | + |
| 67 | + protected function getApiClass() |
| 68 | + { |
| 69 | + // Tell the "getAPIMock" what class to mock. |
| 70 | + return \Github\Api\Gist\Comments::class; |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
0 commit comments