unit-testing - 使用 Mockery 进行 Laravel Controller 测试

标签 unit-testing laravel mockery

我尝试用 mock 的方式在 Laravel 中测试我的 Controller 操作。我已经在这里阅读了本教程:

http://culttt.com/2013/07/15/how-to-structure-testable-controllers-in-laravel-4/

我在构造函数中使用 DI,如下所示:

public function __construct(User $user, Cartalyst\Sentry\Sentry $sentry)
{
    $this->user = $user;
    $this->sentry = $sentry;

    ...

}

我的问题是 Controller 中的以下代码:

public function getShow($id)
{
    try
    {
        // this is a problem, because I dont know how to tell mockery, to mock the
        // Userprovider
        $user = $this->sentry->getUserProvider()->findById($id);
        // this is not a problem for me
        $this->user->all();

        ...

我正在尝试使用 Mockery 作为模拟框架。我的问题是如何模拟像 $this->sentry->getUserProvider() 这样的调用(Cartalyst Sentry 是一个高级授权包)。为了模拟我写的用户模型:

$this->user = Mockery::mock('Eloquent', 'User');

知道如何模拟 Userprovider 或者我应该以其他方式处理这个问题吗?我想测试我的 UserController 是否根据 id 获取用户详细信息。

最佳答案

您可以对 getUserProvider 方法进行 stub 以返回另一个 stub ,例如

$sentry = m::mock("F\Q\C\N\Sentry");
$userProvider = m::mock("F\Q\C\N\UserProvider");
$sentry->shouldReceive("getUserProvider")->andReturn($userProvider)->byDefault();

$userProvider->shouldReceive("findById")->andReturn(new User);

关于unit-testing - 使用 Mockery 进行 Laravel Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20096769/

相关文章:

内容为CountDownTimer类的Android单元测试方法

angular - 使用 Jasmine 进行测试时如何模拟 MatChipInput

laravel - RelationNotFoundException.php 中的 RelationNotFoundException

php - 如何使用 Axios 使用经过身份验证的 API

php - Laravel Mockery - 使用注入(inject)构造函数的依赖项模拟类

unit-testing - 如何在 Laravel 5 中测试路由,或者尝试 "MockStub"的东西,或者我不知道 TDD

php - mock php测试中的碳对象

python - 如何在测试中为多个函数重用相同的模拟

java - 使用 Junit 测试时如何停止 main 方法调用 sleep() 方法?

laravel - Laravel 中的数据表分页