onsa
12/19/2016 - 4:30 PM

Sample usage of Laravel PHPUnit Test

Sample usage of Laravel PHPUnit Test

<?php

/*
*  php artisan make:test UserTest creates a test
*/

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

class UserTest extends TestCase
{
  public function testBasicExample()
  {
    //  call a route
    $response = $this->call('GET', 'user/profile');
    //  call HTTPS
    ->callSecure('GET', 'user/profile');
    //  call a controller
    ->action('GET', 'HomeController@index');
    ->action('GET', 'UserController@profile', array('user' => 1));
    //  get the view of the response
    $view = $response->original;
    
    //  get a crawler with the call
    $crawler = $this->client->request('GET', '/');
    $this->assertTrue($this->client->getResponse()->isOk());
    ->assertCount(1, $crawler->filter('h1:contains("Hello World!")'));
    //  getContent returns the evaluated string contents of the response
    ->assertEquals('Hello World', $response->getContent());

    ->assertResponseOk();
    ->assertResponseStatus(403);
    ->assertRedirectedTo('something');
    ->assertRedirectedToRoute('route.name');
    ->assertRedirectedToAction('Controller@method');
    
    ->assertViewHas('name');
    ->assertViewHas('age', $value);
    
    ->assertSessionHas('name');
    ->assertSessionHas('age', $value);
    ->assertSessionHasErrors();
    //  session has errors for a given key
    ->assertSessionHasErrors('name');
    //  session has errors for several keys
    ->assertSessionHasErrors(array('name', 'age'));
    //  session has old input
    ->assertHasOldInput();
    
    //  set a user as the currently authenticated one
    $user = new User(array('name' => 'John'));
    $this->be($user);
    
    //  reseed DB
    $this->seed();
    $this->seed('DatabaseSeeder');
    
    //  reset any extra bindings (e.g. mocks) placed in the IoC container since test started
    $this->refreshApplication();
  }
}