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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作