Skip to content

Instantly share code, notes, and snippets.

@fatgy
Created January 5, 2015 04:34
Show Gist options
  • Save fatgy/9bd182344623477142a1 to your computer and use it in GitHub Desktop.
Save fatgy/9bd182344623477142a1 to your computer and use it in GitHub Desktop.
Laravel PHPUnit and Mockery snippets.
  • Always mockery close so put in teardown
class FooControllerTest extends TestCase {

  public function tearDown()
  {
    parent::tearDown();
    Mockery::close();
  }

}
  • How to set cookies
class FooControllerTest extends TestCase {

  public function testIndex()
  {
    $cookieName = 'cookie';
    $cookieValue = 'value'; // value of cookie is string
    
    $this->client
      ->getCookieJar()
      ->set(new Symfony\Component\BrowserKit\Cookie($cookieName, $cookieValue));
    
    //Delete cookie
    $this->client
      ->getCookieJar()
      ->expire($cookieName);
  }

}
  • When want test Redirect::back() so set HTTP_REFERER. Recommended don't use Redirect::back().
class FooControllerTest extends TestCase {

  public function testIndex()
  {
    $this->call(
      'POST',
      '/',
      array(),
      array(),
      array(
        'HTTP_REFERER' => 'http://localhost/backto'
      )
    );

    $this->assertRedirectedTo('http://localhost/backto');
  }
}
  • When do not want mock all method in facade so use partial mock
class FooControllerTest extends TestCase {

  public function testIndex()
  {
    //..
    
    Util::shouldReceive('add')->once();
    Util::getFacadeRoot()->makePartial();
    
    //..
  }
}
  • Mock laravel validator
class FooControllerTest extends TestCase {

  public function testIndex()
  {
    //..
    
    Validator::shouldReceive('make')
      ->once()
      ->andReturn(
        Mockery::mock(
          array(
            'fails' => true
          )
        )
      );
    
    //..
  }
}
  • Mock static method
class Helper {
  public static function validate{
    
  }
}

class FooControllerTest extends TestCase {

  public function testIndex()
  {
    //..
    
    $mock = Mockery::mock('alias:Helper')
              ->shouldReceive('validate')
              ->once();

    $this->app->instance('Helper', $mock);
    
    //..
  }
}
@bartmcleod
Copy link

What is $this->client in the cookie example?

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