Support the ongoing development of Laravel.io →
posted 11 years ago
Testing

Hello guys, 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');
  }

}

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
}

Any suggest are really appreciate.

Last updated 3 years ago.
0

Try ...

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
}
Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

fenos fenos Joined 8 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.