【问题标题】:Unable to pass test with Mock无法通过 Mock 测试
【发布时间】:2014-05-08 05:53:37
【问题描述】:

我正在测试 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');
}

【问题讨论】:

    标签: php testing laravel mocking


    【解决方案1】:

    你的模拟没有返回任何东西,你的 foreach 循环期望一个数组循环。

    尝试设置一个空数组的返回值

    $this->mock
        ->shouldReceive('all')
        ->once()
        ->andReturn(new Illuminate\Database\Eloquent\Collection);
    

    【讨论】:

    • 现在说,Failed asserting that Array () is an instance of class "Illuminate\Database\Eloquent\Collection"
    • 因为您在$this-&gt;assertInstanceOf('Illuminate\Database\Eloquent\Collection', $categories); 上声明您的$categories,您可以返回一个集合。或返回一个数组而不执行 assertInstanceOf。
    猜你喜欢
    • 2017-07-15
    • 2021-07-14
    • 2020-07-13
    • 2022-01-09
    • 1970-01-01
    • 2012-06-08
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多