Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created May 21, 2013 22:37
Show Gist options
  • Star 55 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save JeffreyWay/5623836 to your computer and use it in GitHub Desktop.
Save JeffreyWay/5623836 to your computer and use it in GitHub Desktop.
Testing APIs in Laravel. Thoughts?
<?php
class PhotoApiTest extends TestCase {
public function setUp()
{
parent::setUp();
Route::enableFilters();
Artisan::call('migrate');
Artisan::call('db:seed');
Auth::loginUsingId(1);
// OR:
//$this->be(User::find(1));
}
public function testMustBeAuthenticated()
{
Auth::logout();
$response = $this->call('GET', 'api/v1/photos');
$this->assertEquals('Invalid credentials.', $response->getContent());
}
public function testProvidesErrorFeedback()
{
$response = $this->call('GET', 'api/v1/photos');
$data = $this->parseJson($response);
$this->assertEquals(false, $data->error);
}
public function testFetchesAllPhotosForUser()
{
$response = $this->call('GET', 'api/v1/photos');
$data = $this->parseJson($response);
$this->assertIsJson($data);
$this->assertInternalType('array', $data->photos);
}
public function testCreatesPhoto()
{
$photo = [
'caption' => 'My new photo',
'path' => 'foo.jpg',
'user_id' => 1
];
$response = $this->call('POST', 'api/v1/photos', $photo);
$data = $this->parseJson($response);
$this->assertEquals(false, $data->error);
$this->assertEquals('Photo was created', $data->message);
}
protected function parseJson(Illuminate\Http\JsonResponse $response)
{
return json_decode($response->getContent());
}
protected function assertIsJson($data)
{
$this->assertEquals(0, json_last_error());
}
}
@juanjolainez
Copy link

Hi there!

I am trying to test my API as you do. But I'm getting a problem.

I am trying to test this function:

public function getStatus()
{
    $data = [
        'logged'    => Auth::check(),
    ];

    if ($data['logged']) 
    {           
        Auth::user()->last_active = date('Y-m-d H:i:s');
        Auth::user()->save();
        $data['info'] = Auth::user()->toArray();
        $data['info']['type'] = 'User';
    }
    return Response::json($data);
}

But once it arrives to my test, which is this:

$response = $this->client->request(
                                        'GET',
                                        '/api/status',
                                        array(),
                                        array(),
                                        array(
                                            'CONTENT_TYPE'          => 'application/json',
                                            'Accept' => 'application/json'
                                        )
                                    );
$data = $this->parseJson($response);
$this->assertIsJson($data);

I am getting that $response is an instance of Symfony\Component\DomCrawler\Crawler.

Do you know what should I do to fix this?

Thank you!

@boogie4eva
Copy link

You should use $this->call which returns a response object .

@howtomakeaturn
Copy link

good job! nice sample!

@ssi-anik
Copy link

ssi-anik commented Oct 7, 2016

While testing API, you may need to check the database value on a different endpoint, which is dependent to previous test case. To overcome database migration each time, this is what can help..

http://stackoverflow.com/questions/38573830/how-to-migrate-and-seed-before-the-full-test-suite-in-laravel-with-in-memory-dat

Thanks to you anyway. :)

@jacobshafi
Copy link

What do your routes look like? I am trying to do something very similar to you.

@tonholis
Copy link

Great example!
Do you know how to attach a file for upload AND pass a header like "Authorization: Bearer JhdWQiOiIx..."
Because I didn't find a method on Laravel to test this scenario .

@tucq88
Copy link

tucq88 commented Feb 16, 2017

Could you make an update for verify authentication with Token like JWT for Laravel 5 instead ? @JeffreyWay

@connectkushal
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment