dtz8044 2018-07-09 13:06
浏览 76
已采纳

PHP单元,使用单元测试测试laravel日志消息

I'm using PHPUnit to create a Unit test for a store function that stores data in a database.

Currently, i have a test verifies that it has stored data.

However, I also want to create a test that proves that a laravel log message has been produced if the model save function fails.

The code below shows the store function. The "log::info" is the line I want to test.

Thanks.

public function store(Venue $venue){ 
    $saved =  $venue->save();
    if($saved == false){
        Log::info('Failed to Save Venue'. $venue);
    }
 }

This what I have so far, i pass an empty model that will cause the save to fail due to database constraints

public function test_venue_store_failed(){
   $venue = new Venue();
   $venueRepo = new VenueRepository();
   $this->withExceptionHandling();
   $venueRepo->store($venue);
}
  • 写回答

2条回答 默认 最新

  • doushi4633 2018-07-09 14:49
    关注

    Maybe you can use event listener on Models. using this you can get logs on Create or other Events. Check out the Example Below. Hope to help .

    Info 1.

    <?php
        namespace App;
        use Illuminate\Database\Eloquent\Model;
        use User;
        class Venue extends Model
        {
            protected $fillable = ['title', 'ect..'];
            public static function boot() {
                parent::boot();
                static::created(function($item) {
                    \Log::info('venue.created');
                });
                static::updated(function($item) {
                    \Log::info('venue.created');
                });
                static::deleted(function($item) {
                    \Log::info('venue.created');
                });
    
            }
    
        }
    

    Info 2.

    Also there is an exists method on model

    if ($venue->exists()) {
        // saved 
    } else {
        // not saved
    }
    

    Info 3

    To get the insert queries when $venue->save(); error, you can try to catch the exception like this:

        try{
           $venue = new Venue;
           $venue->fields = 'example';
           $venue->save(); // returns false
        }
        catch(\Exception $e){
           // do task when error
           \Log::info($e->getMessage());   // insert query
        }
    

    Hope this helps :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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