doushui20090526 2014-05-08 05:53
浏览 66
已采纳

无法通过Mock测试

i'm testing laravel controller. Here's the respective route

Route::get('categories', array('as'=>'categories', 'uses'=>'CategoryController@getCategory'));

Here's the controller:

<?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);
    }

}

In the view dashboard.showcategories, i have used foreach to loop through the $categories variable and have then used it.

Now i was trying to test this controller.

<?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);
    }
}

But it's showing an error

There was 1 error:

1) CategoryControllerTest::testGetCategory
ErrorException: Invalid argument supplied for foreach() (View: /var/www/Hututoo/app/views/dashboard/showcategories.blade.php)

However, if i delete following code from the test, it passes.

$this->mock
        ->shouldReceive('all')
        ->once();

$this->app->instance('Category', $this->mock);

How to make this test pass with mockery?

In case you need 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');
}
  • 写回答

1条回答 默认 最新

  • doushou7169 2014-05-08 06:01
    关注

    your mock does not return anything, and your foreach loop is expecting an array to loop over.

    try setting a return value of an empty array

    $this->mock
        ->shouldReceive('all')
        ->once()
        ->andReturn(new Illuminate\Database\Eloquent\Collection);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)