Laravel 5.0用户雄辩的模型嘲弄

时间:2015-10-10 16:06:35

标签: php laravel testing phpunit mockery

我一直试图在我的Laravel应用程序的控制器测试中使用Mockery一段时间,但似乎没有任何效果。

UserController.php:

class UserController extends Controller
{
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Display a listing of the resource.
     * GET /user
     *
     * @return Response
     */
    public function index()
    {
        $users = $this->user->orderBy('created_at', 'desc')->paginate(6);
        return view('users.index', compact('users'));
    }
}

我的测试:

class UserControllerTest extends TestCase {

    protected $user;
    protected $builder;
    protected $paginator;

    public function setUp()
    {
        parent::setUp();
    }

    public function tearDown()
    {
        Mockery::close();
    }

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testIndex()
    {
        $this->user = Mockery::mock('App\User');

        $this->user
            ->shouldReceive('orderBy')
            ->once()
        ;

        $this->app->instance('App\User', $this->user);
        $response = $this->call('GET', 'users');

        $this->assertEquals(200, $response->getStatusCode());
    }

}

当我运行PHPUnit时,我得到输出:

[Symfony的\元器件\调试\异常\ FatalErrorException]
  在非对象上调用成员函数paginate()

当我添加 - > andReturn($ this-> user)时:

$this->user
        ->shouldReceive('orderBy')
        ->once()
        ->andReturn($this->user)
 ;

我得到PHPUnit输出:

Failed asserting that 500 matches expected 200.
Expected :200
Actual   :500

当我打印响应时,它内部有以下错误:

Method Mockery_0_App_User::paginate() does not exist on this mock object

当我模仿paginate()函数时,它再次失败了' getIterator'视图中的功能。

那么我做错了什么? 我在这里看过教程,阅读文章和相关答案,但尚未找到解决方案。

1 个答案:

答案 0 :(得分:1)

你必须模拟paginate,它必须返回一个用户数组。

您的期望应如下所示:

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing Activity")
        .setMessage("Are you sure you want to close this activity?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .setNegativeButton("No", null)
    .show();
}

其中$this->user ->shouldReceive('orderBy->paginate') ->once() ->andReturn($userArray); 是一个数组,表单上有用户,您将在视图中使用它。我想这就是你得到“getIterator”错误的原因,可能你会返回一些无法正确迭代的东西。