Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock App::make() on UnitTesting Laravel 4

i got a question when i was unit testing my application. I Have a method that require a dependency but only that method need it so i thought to don't inject it by construct but initialize it with App::make() of the IoC container Class. But now how can i unit test that?

Let's say a short example for understand how you unit testing this function of example

class Example {

  public function methodToTest()
  {
       $dependency = App::make('Dependency');
       return $dependency->method('toTest');
  }

}

Test

public function test_MethodToTest() {
  $dependency =  m::mock('Dependency');
  $dependency->shouldReceive('method')->once()->with('toTest')->andReturn(true);

  $class = new Example();
  $this->assertTrue($class->methodToTest('toTest')); // does not work
}
like image 554
Fabrizio Fenoglio Avatar asked Feb 27 '14 16:02

Fabrizio Fenoglio


1 Answers

You're almost there. Create an anonymous mock with the expectations that you need and then register that mock as the instance for Dependency and you should be good to go.

That would look something like this

public function test_MethodToTest() {
    $dependency =  m::mock();
    $dependency->shouldReceive('method')->once()->with('toTest')->andReturn(true);
    App::instance('Dependancy', $dependancy);

    $class = new Example();
    $this->assertTrue($class->methodToTest()); // should work
}
like image 134
petercoles Avatar answered Oct 21 '22 20:10

petercoles