我正在测试laravel控制器。 这是相应的路线
Route::get('categories', array('as'=>'categories', 'uses'=>'CategoryController@getCategory'));
这是控制器:
<?php
// app/controllers/CategoryController.php
class CategoryController extends BaseController {
//Loading Category model instance in constructor
public function __construct(Category $category){
$this->category = $category;
}
public function getCategory(){
$categories = $this->category->all();
return View::make('dashboard.showcategories')->with('categories', $categories);
}
}
在视图dashboard.showcategories
中,我使用foreach循环遍历$categories
变量,然后使用它。
现在我正试图测试这个控制器。
<?php
// app/tests/controllers/CategoryControllerTest
class CategoryControllerTest extends TestCase {
public function __construct(){
$this->mock = Mockery::mock('Eloquent', 'Category');
}
public function tearDown(){
Mockery::close();
}
public function testGetCategory(){
$this->mock
->shouldReceive('all')
->once();
$this->app->instance('Category', $this->mock);
$response = $this->call('GET', 'categories');
$categories = $response->original->getData()['categories'];
$this->assertViewHas('categories');
$this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $categories);
}
}
但它显示错误
There was 1 error:
1) CategoryControllerTest::testGetCategory
ErrorException: Invalid argument supplied for foreach() (View: /var/www/Hututoo/app/views/dashboard/showcategories.blade.php)
但是,如果我从测试中删除了以下代码,它就会通过。
$this->mock
->shouldReceive('all')
->once();
$this->app->instance('Category', $this->mock);
如何让这个测试通过嘲弄?
如果您需要Category model
<?php
// app/models/Category.php
use Jenssegers\Mongodb\Model as Eloquent;
class Category extends Eloquent {
protected $table = 'category';
protected $fillable = array('category_name', 'options');
}
答案 0 :(得分:1)
你的模拟器没有返回任何东西,你的foreach循环期望一个数组循环。
尝试设置空数组的返回值
$this->mock
->shouldReceive('all')
->once()
->andReturn(new Illuminate\Database\Eloquent\Collection);