使用Mockery进行Laravel控制器测试

时间:2013-11-20 13:04:01

标签: unit-testing laravel mockery

我尝试用嘲弄来测试我在laravel中的控制器动作。我已经在这里阅读了这个教程:

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;

    ...

}

我的问题是我的控制器中的以下代码:

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或者我应该以另一种方式处理它吗?如果我根据id获取用户详细信息,我想测试我的UserController。

1 个答案:

答案 0 :(得分:2)

您可以将getUserProvider方法存根以返回另一个存根,例如

$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);