Yes you should use andReturn so your mock returns a dummy collection of models.
Testing Controller
Hey,
I'm trying to unit test a controller. I know most of you (including me) would just use a functional / acceptance test for this. But, I want to give this a go just so I know how to do it. Anyways, mockery is new to me also so I'm guessing a controller would not be a great starting point but shrugs
Here's my controller
<?php
use CookBook\Recipes\RecipeRepository;
class HomeController extends BaseController {
/**
* @var RecipeRepository
*/
protected $recipe;
/**
* @param RecipeRepository $recipe
*/
public function __construct(RecipeRepository $recipe)
{
$this->recipe = $recipe;
}
/**
* @return \Illuminate\View\View
*/
public function index()
{
$recipes = $this->recipe->getAllPaginated();
return View::make('home.index', compact('recipes'));
}
}
So to test this I need to assert get all paginated has been called once and the view has the recipes variable available right?
Here's my test
<?php
class HomeControllerTest extends TestCase {
public function tearDown()
{
Mockery::close();
}
/**
* @test
* @return void
*/
public function index()
{
$mock = Mockery::mock('CookBook\Recipes\RecipeRepository');
$this->app->instance('CookBook\Recipes\RecipeRepository', $mock);
$mock->shouldReceive('getAllPaginated')->once();
$this->call('GET', '/');
$this->assertResponseOk();
$this->assertViewHas('recipes');
}
}
(just for reference)
public function getAllPaginated($howMany = 12)
{
return $this->model->with('user', 'tags')->latest()->paginate($howMany);
}
The error i get is this
FATAL ERROR. TESTS NOT FINISHED. Call to a member function chunk() on null
That's perfectly understandable, you can't call chunk on null as my mock does not return anything.
What do I need to set ->andReturn to? Or what would you do differently to make this a legit test?
Cheers
Please or to participate in this conversation.