Search code examples
phpunit-testinglaravel-5.3

Testing API in Laravel 5.3


I am new in Laravel and I am a bit confused on how to test my api in 5.3. I read the docs and I saw this kind of examples but I don't know if I applied the examples correctly. Anyway, I'm always getting an ErrorException

Error Exception

I have this one in UserTest.php

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserTest extends TestCase
{
   /**
    * A basic test example.
    *
    * @return void
   */
   public function testLoginSuccess()
   {
       $this->post('http://127.0.0.1/identificare_api/public/api/user/login', ['email' => '[email protected]', 'password' => 'identificare']);
   }
}

and I tried this one also, still no go.

$this->json('POST', 'user/login', ['email' => '[email protected]', 'password' => 'identificare']);

here's my route

Route::post('user/login', 'UserController@login');

Is it correct to do it this way? If no, what's the correct way of testing my api?


Solution

  • Correct way to call the post is

    $this->post('/user/login', array('email' => '[email protected]', 'password' => 'identificare'));
    

    or

    $this->call('POST','/user/login', array('email' => '[email protected]', 'password' => 'identificare'));
    

    use an echo and exit in the login function and check whether test hitting the controller function. It will be easier if you share a dummy code of your controller function ,because we could n`t figure out what this variable $e. Which should be in controller.