模拟静态 Eloquent 模型方法,包括 find()

2024-01-06

我一直在关注一般的 Mockery 和 PHP-Unit 教程 - 包括 Jeffrey Way 的关于使用 PHP-Unit 和 Mockery 测试 Laravel 的介绍。然而,对于这个应用程序 - 我们可以接受对 Eloquent 的依赖,并且不想创建存储库类。

我们能够很好地模拟 Widget 模型的实例方法。然而,我们正在使用 Route:model 绑定,我承认我不太确定在测试控制器的 show($widget) 方法时如何模拟模型的 find() 方法。

我读了https://github.com/padraic/mockery/wiki#mocking-public-static-methods https://github.com/padraic/mockery/wiki#mocking-public-static-methods文档,并看到“别名”前缀可以放置在要模拟的类前面。但我似乎也无法让它发挥作用。

这是routes.php...

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

这是(缩短的)控制器......

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

}

这是测试装置。

# /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']);

    }
}

testShow 方法上的错误是:调用未定义的方法 Widget::find()

想法?


好的 - 删除了 Route 模型绑定,并将一个对象返回到模拟模型的视图。

控制器https://github.com/58bits/laravel-4-bootstrap-3-starter/blob/master/app/controllers/WidgetController.php 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://github.com/58bits/laravel-4-bootstrap-3-starter/blob/master/app/tests/controllers/WidgetControllerTest.php

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模拟静态 Eloquent 模型方法,包括 find() 的相关文章

随机推荐

  • 使用有关 WooCommerce 用户创建的生成密码发送电子邮件通知

    在 WooCommerce 中 使用下面的代码我创建新的 WP User 其中随机密码并将用户角色设置为 客户 我想在购买时自动创建帐户 然后我用WC Emails将登录详细信息发送给买家 在这种情况下 我需要纯密码 但我真的不知道为什么附
  • 如何锁定 SVN 主干(除了来自分支的合并)?

    我想阻止开发人员直接在主干上工作 我的目标是强制所有开发人员离开主干并在自己的分支上工作 直到 CI 测试通过 然后 他们必须从主干合并到分支 以获取最新更改 运行并通过测试 然后再合并回主干 这种 SVN 使用方式有什么规则吗 限制主干提
  • “grep”命令的退出状态代码

    The grep http linux die net man 1 grep手动在退出状态部分报告 EXIT STATUS The exit status is 0 if selected lines are found and 1 if
  • CTE 的意外结果

    我创建了一个使用多个 CTE 的复杂流程 主要用于递归分层工作 在小样本数据集上 一切都按预期进行 但是当我将代码应用于大数据集时 我收到了意外 且错误 的结果 我想我已经将范围缩小到了 CTE 递归 CTE 是在几个早期 CTE 中处理的
  • 在 Datalab 中查询 Hive 表时出现问题

    我已经创建了一个 dataproc 集群 其中包含更新的 init 操作来安装 datalab 一切正常 除了当我从 Datalab 笔记本查询 Hive 表时 我遇到了 hc sql select from invoices limit
  • Chrome 扩展:点击编辑当前网址,然后重定向到编辑后的网址

    我是一名心理学学生 我经常阅读论文 大学图书馆提供数据库的访问 但我每次都需要使用图书馆搜索引擎并登录 很烦人 我找到了一种避免跳转页面的方法 方法如下 我在Google Scholar中找到一篇论文后 在目标数据库地址末尾添加 ezp l
  • Symfony2 SonataAdminBundle 密码字段加密

    我有 FOSUserBundle 来管理我的用户 SonataAdminBundle 来管理我的网站 我有一个问题 每当我尝试更改 添加任何用户的密码时 密码都不会编码到sha512 但是当用户在 fosuserbundle 注册页面中注册
  • SQLite查询:获取一行的所有列(android)?

    这是架构 SQL查询是 从unjdat中选择 其中col 1 myWord 即 我想显示 col 1 为的行的所有列myWord int i String temp words new ArrayList
  • 如何使用正则表达式将缩写与其含义相匹配?

    我正在寻找与以下字符串匹配的正则表达式模式 一些示例文本 SET 演示了我正在寻找的内容 能源系统模型 ESM 用于寻找特定的最佳值 SCO 有人说计算机系统 CUST 很酷 夏天应该首选户外比赛 OUTS 我的目标是匹配以下内容 Some
  • 使用函数触发 chrome.browserAction.onClicked

    我想触发点击 以下代码正在侦听 chrome browserAction onClicked addListener function tab 原因是我有一个工作扩展 它正在后台脚本 上面的 addListener 中监听并在单击时执行一些
  • JavaScript 数组迭代返回多个值

    这太简单了 我感到困惑 我有以下内容 var x shrimp var stypes new Array shrimp crabs oysters fin fish crawfish alligator for t in stypes if
  • 动态改变任务重试次数

    重试任务可能毫无意义 例如 如果任务是传感器 并且由于凭据无效而失败 那么以后的任何重试都将不可避免地失败 如何定义可以决定重试是否合理的操作员 在 Airflow 1 10 6 中 决定任务是否应该重试的逻辑位于airflow model
  • SQLite 连接未出现在实体数据模型向导中(vs2015)

    我所做的是 1 在vs2015 Net Framework 4 6 中创建一个项目 2 从Nuget安装System Data SQLite 实际上是System Data SQLite 1 0 105 1 System Data SQLi
  • Spring JDBC 和 Firebird 数据库

    有没有人actually将 Firebird 2 1 与 Spring JDBC 一起使用 出于测试目的 我在 MySQL Postgres 和 Firebird 中设置了三个简单的单表数据库 我在连接 MySQL 或 Postgres 并
  • xml 中的 Android xml 引用不起作用

    我想将新的材料设计应用到我的 Android 应用程序中 但我的 xml 文件有一个小问题
  • 在SearchView中处理物理键盘的Enter键

    我在我的应用程序中实现了一个 SearchView 当我使用软键盘 使用查询文本监听器 https developer android com reference android widget SearchView OnQueryTextL
  • $watch 一个服务变量或者 $broadcast 一个带有 AngularJS 的事件

    我正在使用一项服务在控制器之间共享数据 当变量被修改时 应用程序必须更新 DOM 我找到了两种方法来做到这一点 您可以在此处查看代码 http jsfiddle net sosegon 9x4N3 7 http jsfiddle net s
  • Java - 通过对象数组调用扩展类中的函数

    我有一个对象数组 其中一些使用扩展版本 其中包含基类中不可用的函数 当数组是由基类定义时 如何通过数组调用该函数 Example Shape shapes new Shape 10 shapes 0 new Circle 10 10 rad
  • 解释 gcov 输出以识别基本块

    我使用 gcov 和手册中的选项 a all blocks When you use the a option you will get individual block counts 原始文件 include
  • 模拟静态 Eloquent 模型方法,包括 find()

    我一直在关注一般的 Mockery 和 PHP Unit 教程 包括 Jeffrey Way 的关于使用 PHP Unit 和 Mockery 测试 Laravel 的介绍 然而 对于这个应用程序 我们可以接受对 Eloquent 的依赖