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

时间:2014-02-27 16:22:58

标签: unit-testing mocking laravel-4

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

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

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
}

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

我更愿意在Example类构造函数中注入依赖项。

class Example{
    /** @var Dependency */
    private $dependency;

    public function __construct(Dependency $dependency){
        $this->dependency = $dependency;
    }

    public function methodToTest(){
        return $this->dependency->method('toTest');
    }
}

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

        $class = new Example($mock);
        $this->assertTrue($class->methodToTest());
    }
}

在您的控制器库中,您可以像这样使用IoC

$example = App::make(Example::class);