Mocking Static Eloquent Models Methods including find()

最后都变了- 提交于 2019-12-14 00:32:28

问题


I've been following the general Mockery and PHP-Unit tutorials - including Jeffrey Way's introduction to testing Laravel with PHP-Unit and Mockery. However, for this app - we're fine with a dependency on Eloquent, and would rather not create a repository class.

We're able to mock instance methods of our Widget model fine. However, we're using Route:model binding and I confess I'm not exactly sure how to mock the find() method of the model when testing the show($widget) method of the controller.

I've read https://github.com/padraic/mockery/wiki#mocking-public-static-methods docs, and see that an 'alias' prefix can be placed in front of the class to be mocked. But I can't seem to get this to work either.

Here's routes.php...

Route::model('widgets', 'Widget');
Route::resource('widgets', 'WidgetController');

Here's the (shortened) controller...

<?php
/*
|--------------------------------------------------------------------------
| Widget Controller
|--------------------------------------------------------------------------
|
| An example controller that uses the pre-baked RESTful resource controller
| actions for index, create, store, show, edit, update, destroy, as well as a
| delete method to show the record before deletion.
|
| See routes.php  ->
| Route::resource('widget', 'WidgetController');
| Route::get('widget/{widget}/delete', 'WidgetController@delete');
|
*/

class WidgetController extends BaseController
{
    /**
     * Widget Model
     * @var Widget
     */
    protected $widget;

    /**
     * Inject the model.
     * @param Widget $widget
     */
    public function __construct(Widget $widget)
    {
        parent::__construct();
        $this->widget = $widget;
    }

    /**
     * Display a listing of the resource.
     *
     * See public function data() below for the data source for the list,
     * and the view/widget/index.blade.php for the jQuery script that makes
     * the Ajax request.
     *
     * @return Response
     */
    public function index()
    {
        // Title
        $title = Lang::get('widget/title.widget_management');

        // Show the page
        return View::make('widget/index', compact('title'));
    }

    /**
     * Show a single widget details page.
     *
     * @return View
     */
    public function show($widget)
    {
        // Title
        $title = Lang::get('widget/title.widget_show');

        // Show the page
        return View::make('widget/show', compact('widget', 'title'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        // Title
        $title = Lang::get('widget/title.create_a_new_widget');

        // Show the page
        return View::make('widget/create', compact('title'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        // Validate the inputs
        $rules = array(
            'name'=> 'required|alpha_dash|unique:widgets,name',
            'description'=> 'required'
            );

        // Validate the inputs
        $validator = Validator::make(Input::all(), $rules);

        // Check if the form validates with success
        if ($validator->passes()) {
            // Get the inputs, with some exceptions
            $inputs = Input::except('csrf_token');

            $this->widget->name = $inputs['name'];
            $this->widget->description = $inputs['description'];
            $this->widget->save($rules);

            if ($this->widget->id) {
                // Redirect to the new widget page
                return Redirect::to('widgets')->with('success', Lang::get('widget/messages.create.success'));

            } else {
                // Redirect to the widget create page
                //var_dump($this->widget);
                return Redirect::to('widgets/create')->with('error', Lang::get('widget/messages.create.error'));
            }
        } else {
            // Form validation failed
            return Redirect::to('widgets/create')->withInput()->withErrors($validator);
        }
    }

}

And here's the test fixture.

# /app/tests/controllers/WidgetControllerTest.php

class WidgetControllerTest extends TestCase
{
    public function __Construct()
    {
        $this->mock = Mockery::mock('Eloquent', 'Widget');
    }

    public function setUp()
    {
        parent::setUp();

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

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

    /**
     * Index
     */
    public function testIndex()
    {
        $this->call('GET', 'widgets');

        $this->assertTrue($this->client->getResponse()->isOk());
        $this->assertViewHas('title');
    }

    /**
     * Show
     */
    public function testShow()
    {
        //$this->mock->shouldReceive('find')->with(1)->once()->andReturn(array('id'=>1));

        $this->mock
        ->shouldReceive('find')
        ->once()
        ->andSet('id', 1);

        //$this->call('GET', 'widgets/1');
        $this->action('GET', 'WidgetController@show', array(
            'widgets' => 1
            ));

        $this->assertTrue($this->client->getResponse()->isOk());
    }

    /**
     * Create
     */
    public function testCreate()
    {
        $crawler = $this->client->request('GET', 'widgets/create');

        $this->assertTrue($this->client->getResponse()->isOk());
        $this->assertViewHas('title');
        $this->assertCount(1, $crawler->filter('h3:contains("Create a New Widget")'));

    }

    /**
     * Store Success
     */
    public function testStoreSuccess()
    {
        $this->mock
        ->shouldReceive('save')
        ->once()
        ->andSet('id', 1);

        $this->call('POST', 'widgets', array(
            'name' => 'Fu-Widget',
            'description' => 'Widget description'
            ));

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

    /**
     * Store Fail
     */
    public function testStoreFail()
    {

        $this->call('POST', 'widgets', array(
            'name' => '',
            'description' => ''
            ));

        $this->assertRedirectedToRoute('widgets.create');
        $this->assertSessionHasErrors(['name']);

    }
}

There error on the testShow method is: Call to undefined method Widget::find()

Thoughts?


回答1:


Okay - removed Route model binding, and returned an object to the view that mocks the model.

Controller https://github.com/58bits/laravel-4-bootstrap-3-starter/blob/master/app/controllers/WidgetController.php

Tests https://github.com/58bits/laravel-4-bootstrap-3-starter/blob/master/app/tests/controllers/WidgetControllerTest.php



来源:https://stackoverflow.com/questions/19753502/mocking-static-eloquent-models-methods-including-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!