繁体   English   中英

模拟Laravel控制器依赖

[英]Mocking Laravel controller dependency

在我的Laravel应用程序中,我有一个控制器,其中包含显示特定资源的方法。 例如,假设url是/widgets/26我的控制器方法可能会这样工作:

Class WidgetsController {
    protected $widgets;

    public function __construct(WidgetsRepository $widgets)
    {
        $this->widgets = $widgets;
    }

    public function show($id)
    {
        $widget = $this->widgets->find($id);

        return view('widgets.show')->with(compact('widget'));
    }
}

我们可以看到我的WidgetsController有一个WidgetsRepository依赖项。 show方法的单元测试中,我如何模拟这个依赖项,以便我实际上不必调用存储库而只是返回一个硬编码的widget

单元测试开始:

function test_it_shows_a_single_widget()
{
    // how can I tell the WidgetsController to be instaniated with a mocked WidgetRepository?
    $response = $this->action('GET', 'WidgetsController@show', ['id' => 1]);

    // somehow mock the call to the repository's `find()` method and give a hard-coded return value
    // continue with assertions
}

您可以模拟存储库类并将其加载到IoC容器中。

因此,当Laravel到达你的控制器时,它会发现它已经在那里并将解析你的模拟而不是实例化一个新模拟器。

function test_it_shows_a_single_widget()
{
    // mock the repository
    $repository = Mockery::mock(WidgetRepository::class);
    $repository->shouldReceive('find')
        ->with(1)
        ->once()
        ->andReturn(new Widget([]));

    // load the mock into the IoC container
    $this->app->instance(WidgetRepository::class, $repository);

    // when making your call, your controller will use your mock
    $response = $this->action('GET', 'WidgetsController@show', ['id' => 1]);

    // continue with assertions
    // ...
}

类似的设置已经过测试,在Laravel 5.3.21中运行良好。

Laracasts也有类似的问题。 这个人有类似的东西( https://laracasts.com/discuss/channels/general-discussion/mockery-error?page=1 ):

public function testMe()
{
    // Arrange
    $classContext = Mockery::mock('\FullNamespace\To\Class');
    $classContext->shouldReceive('id')->andReturn(99);
    $resources = new ResourcesRepo($classContext);

    // Act

   // Assert
}

但是,如果使用PHPUnit方法( http://docs.mockery.io/en/latest/reference/phpunit_integration.html ),您也可以将它放在setUp方法上。

希望这是有帮助的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM