lundi 26 janvier 2015

Why Mockery appears to ignore the method it should mock?

I'm using Laravel and unit testing with PHPUnit and Mockery.

I've created an repository and a form validator and injected them into the controller. In my list methods the controller uses the repository to list the items, and the store and update should use the form validator, however, on my tests I received errors from Mockery saying that the "Method create(array('name'=>'Test',))", should be called 1 or more times.


My test class:



<?php namespace MyProject\Controllers\Dashboard;
use \Mockery;
class CategoriesControllerTest extends \TestCase
{
private $category;
private $form;

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

public function testCanListCategories()
{
$page = 1;
$perPage = 10;
$categoryInstance = '\MyProject\Repositories\Category\CategoryInterface';
$this->category = Mockery::mock($categoryInstance);
$this->app->instance($categoryInstance, $this->category);

$data = new \stdClass();
$data->items = [];
$data->total = 15;

$this->category->shouldReceive('byPage')
->once()
->with($page, $perPage)
->andReturn($data);

$this->route('GET', 'dashboard.categories.index');

$this->assertResponseOk();
$this->assertViewHas('categories');
}

public function testCanStoreANewCategory()
{
$formInstance = '\MyProject\Services\Form\Category\CategoryForm';
$this->form = Mockery::mock($formInstance);
$this->app->instance($formInstance, $this->form);

$this->form->shouldReceive('create')->once()->with(['name' => 'Test'])->andReturn(true);

$this->route('POST', 'dashboard.categories.store', null, ['name' => 'Test']);

$this->assertRedirectedToRoute('dashboard.categories.index');
}
}


My Controller:



<?php namespace MyProject\Controllers\Dashboard;

use \MyProject\Repositories\Category\CategoryInterface;
use \MyProject\Services\Form\Category\CategoryForm;

class CategoriesController extends \BaseController
{
protected $category;
protected $form;
protected $perPage;

public function __construct(CategoryInterface $category, CategoryForm $form)
{
$this->category = $category;
$this->form = $form;
$this->perPage = 10;
}

public function index()
{
$page = \Input::get('page', 1);

$data = $this->category->byPage($page, $this->perPage);
$categories = \Paginator::make($data->items, $data->total, $this->perPage);

return \View::make('dashboard.categories.index')
->withCategories($categories);
}

public function create()
{
return \View::make('dashboard.categories.create');
}

public function store()
{
if ($this->form->create(\Input::all()) )
{
return \Redirect::route('dashboard.categories.index')->withMessage('New category created!');
}
return \Redirect::route('dashboard.categories.create')
->withErrors($this->form->errors());
}
}


It appears that Mockery have ignored the method, but on the the other test it calls byPage normally.


Aucun commentaire:

Enregistrer un commentaire