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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?