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

图片转代码服务由CSDN问答提供 功能建议

我正在使用PHPUnit为存储数据的商店函数创建单元测试。

目前,我有一个测试验证它是否存储了数据。

但是,我还想创建一个测试,证明如果模型保存功能失败,则会生成一个laravel日志消息。

下面的代码显示了商店功能。 “log :: info”是我要测试的行。

感谢。

 公共功能商店(Venue $场地){
 $ saved = $ venue-> save(); 
 if($ saved == false){
  Log :: info('无法保存场地'。$场地); 
} 
} 
   
 
 

这是我到目前为止,我通过一个空 由于数据库约束导致保存失败的模型

  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条)

相关推荐 更多相似问题