[英]Laravel 5.0 User Eloquent Model Mockery
I have been trying to use Mockery in my Laravel application's Controller tests for some time, but nothing seems to work. 我一直在尝试在Laravel应用程序的Controller测试中使用Mockery,但是似乎没有任何效果。
UserController.php: 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'));
}
}
My Test: 我的测试:
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());
}
}
When I run PHPUnit I get output: 当我运行PHPUnit时,我得到输出:
[Symfony\\Component\\Debug\\Exception\\FatalErrorException] [Symfony的\\元器件\\调试\\异常\\ FatalErrorException]
Call to a member function paginate() on a non-object 在非对象上调用成员函数paginate()
When I add ->andReturn($this->user) : 当我添加-> andReturn($ this-> user)时:
$this->user
->shouldReceive('orderBy')
->once()
->andReturn($this->user)
;
I get PHPUnit output of: 我得到PHPUnit输出:
Failed asserting that 500 matches expected 200.
Expected :200
Actual :500
And when I print the response it has the following error inside it: 当我打印响应时,它内部有以下错误:
Method Mockery_0_App_User::paginate() does not exist on this mock object
When I mock the paginate() function it just fails again on 'getIterator' function in the View. 当我模拟paginate()函数时,它在View中的'getIterator'函数上再次失败。
So what am I doing wrong? 那我在做什么错? I watched tutorials, read articles and related answers here, but haven't found a solution yet. 我在这里看了教程,阅读了文章和相关的答案,但是还没有找到解决方案。
You would have to mock paginate and it has to return an array of users. 您将不得不模拟分页,并且它必须返回一个用户数组。
Your expectation should look like this: 您的期望应如下所示:
$this->user
->shouldReceive('orderBy->paginate')
->once()
->andReturn($userArray);
where $userArray
is an array with users on the form you would use it in the view. 其中$userArray
是一个数组,其中有用户,您将在视图中使用该窗体。 I guess that's why you get the "getIterator" error, probably you return something that can't be iterated properly. 我猜这就是为什么会出现“ getIterator”错误的原因,可能您返回了无法正确迭代的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.