如何在UnitTesting Laravel 4上模拟App :: make()

Fab*_*lio 9 unit-testing mocking laravel-4

我在单元测试我的应用程序时遇到了一个问题.我有一个需要依赖的方法,但只有那个方法需要它,所以我想不要用构造注入它,而是用IoC容器类的App :: make()初始化它.但是现在我怎么能进行单元测试呢?

让我们举一个简短的例子来理解你如何对这个函数进行单元测试

class Example {

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

}
Run Code Online (Sandbox Code Playgroud)

测试

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
}
Run Code Online (Sandbox Code Playgroud)

pet*_*les 20

你快到了.创建一个具有您需要的期望的匿名模拟,然后将该模拟注册为Dependency的实例,您应该很高兴.

这看起来像这样

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
}
Run Code Online (Sandbox Code Playgroud)