doupin5408 2013-09-19 19:04
浏览 54
已采纳

Laravel - 单元测试模型保存

I am working on mocking a save function in Laravel for testing. I have a saving() event that I am trying to test. I have tried using Eloquent::shouldReceive('save') but it gives a fatal error: Fatal error: Cannot instantiate abstract class Illuminate\Database\Eloquent\Model.

This is my test so far:

public function testRemoveAttributesOnSave(){
    Eloquent::shouldReceive('save')->once()->andReturn(true);
    $this->model->attributeA=1;
    $this->model->attributeB=2;
    $this->model->save();
    $this->assertTrue(!isset($this->model->attributeB));
}

What I want to write is self explanatory on the test. I am trying to handle the validation in the model, and protect some attributes from being included after saving.

If I am going about this wrong, please let me know.

  • 写回答

1条回答 默认 最新

  • dongxixia6399 2013-09-24 07:25
    关注

    I did a search and found an answer in a comment here on SO

    When you use model events (public static function boot()), PHPUnit does not register the events and they go ignored. Now it remains to be answered as to whether this is PHPUnit's fault or Laravel's fault, but hopefully it is something that will be addressed in future releases.

    To overcome the issue, you need to manually call the boot() method in your unit test, and you can do it in the setUp():

    public function setUp(){
        parent::setUp();
        Artisan::call('migrate');
        $this->seed();
        $this->model=new User;
        User::boot();
    }
    

    Hope this helps anyone using Laravel and working on unit testing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助