简体   繁体   English

使用Mockery的Laravel控制器测试

[英]Laravel Controller testing with Mockery

I try to test my controller actions in laravel with mockery. 我尝试用嘲讽来测试laravel中的控制器动作。 I already read this tutorial here: 我已经在这里阅读了本教程:

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

I use DI in my constructor like this: 我在构造函数中使用DI像这样:

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

    ...

}

My problem is the following code in my 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();

        ...

I am trying to work with Mockery as a mock framework. 我正在尝试将Mockery作为模拟框架使用。 My question is how to mock a call like $this->sentry->getUserProvider() (Cartalyst Sentry is a advanced authorization bundle). 我的问题是如何模拟像$ this-> sentry-> getUserProvider()这样的调用(Cartalyst Sentry是高级授权捆绑包)。 To mock the User Model i write: 模拟我写的用户模型:

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

Any idea how to mock the Userprovider or should I handle this in another way ? 任何想法如何嘲笑Userprovider还是应该以其他方式处理呢? I want to test my UserController if I am getting the user details depending on the id. 如果要根据ID获取用户详细信息,我想测试UserController。

You can stub the getUserProvider method to return another stub, eg 您可以对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);

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

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