I have been trying to use Mockery in my Laravel application's Controller tests for some time, but nothing seems to work.
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:
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function paginate() on a non-object
When I add ->andReturn($this->user) :
$this->user
->shouldReceive('orderBy')
->once()
->andReturn($this->user)
;
I get PHPUnit output of:
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.
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. I guess that's why you get the "getIterator" error, probably you return something that can't be iterated properly.