php - 模拟 Laravel Controller 依赖

标签 php unit-testing laravel phpunit

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

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 到达你的 Controller 时,它会发现它已经在那里并且会解析你的模拟而不是实例化一个新的。

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 中运行良好。

关于php - 模拟 Laravel Controller 依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721238/

相关文章:

php - Amazon SES : Message sending failed - The following SMTP error was encountered: 552 5. 3.4 消息太长

PHP/FFMPEG - 为什么我的视频转换会导致空文件?

php - 在 PHP 中为记录器使用静态方法或对象更好吗?

unit-testing - 通过扩展 WebTestCase 使 Symfony2 单元测试更加 DRY

node.js - Lumen (Laravel) 与 NODE.JS 解决方案

php - 如何将 laravel 项目移动到 ubuntu 中的本地主机?

php - 哪个 PHP 框架与 Twitter Bootstrap

c# - 如何模拟存储库/工作单元

java - 如何在 Spring Boot 中的所有测试用例之前仅设置一次独立 Controller ?

laravel - 如何在另一个文件中包含 Blade 模板?