我正在尝试用这个测试来测试我的控制器(如果这很重要,我正在使用 Laravel):
<?php
use Zizaco\FactoryMuff\Facade\FactoryMuff;
class ProjectControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->mock = $this->mock('Dumminvoicing\Storage\Project\ProjectRepositoryInterface');
}
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
protected function tearDown()
{
Mockery::close();
}
public function testRedirectWhenNotLogged()
{
Route::enableFilters();
$response = $this->call('GET', 'projects');
$this->assertRedirectedToAction('UserController@getLogin');
}
public function testAllowedWhenLogged()
{
Route::enableFilters();
//Create user and log in
$user = FactoryMuff::create('User');
$this->be($user);
$response = $this->call('GET', 'projects');
$this->assertResponseOk();
}
public function testIndex()
{
$this->mock->shouldReceive('all')->once();
$this->call('GET', 'projects');
$this->assertViewHas('projects');
}
}
按照这些教程http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/ http://culttt.com/2013/07/15/how-to -structure-testable-controllers-in-laravel-4/我使用存储库来避免将我的数据库耦合到测试。所以我有这两个额外的课程:
<?php
namespace Dumminvoicing\Storage\Project;
use Project;
class EloquentProjectRepository implements ProjectRepository
{
public function all()
{
return Project::all();
}
public function find($id)
{
return Project::find($id);
}
}
<?php
namespace Dumminvoicing\Storage\Project;
interface ProjectRepository
{
public function all();
public function find($id);
}
当我运行测试时,我得到这个错误:
有 1 个错误:
1) ProjectControllerTest::testIndex Mockery\Exception\InvalidCountException: 来自 Mockery_2143809533_Dumminvoicing_Storage_Project_ProjectRepositoryInterface 的方法 all() 应准确调用 1 次,但调用 0 次。
控制器的 index 方法在浏览器中运行良好:
use Dumminvoicing\Storage\Project\ProjectRepository as Project;
class ProjectsController extends \BaseController
{
protected $project;
public function __construct(Project $project)
{
$this->project = $project;
$this->beforeFilter('auth');
}
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$data['projects'] = $this->project->all();
return View::make('projects.index', $data) ;
}
那么为什么它在测试中失败了呢?为什么不调用“全部”?