【问题标题】:PHP Unit, Testing laravel log messages with unit testingPHP 单元,使用单元测试测试 laravel 日志消息
【发布时间】:2018-12-17 04:25:01
【问题描述】:

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

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

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

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

谢谢。

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

这是我目前所拥有的,我传递了一个空模型,由于数据库限制,该模型将导致保存失败

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

【问题讨论】:

  • 也许像if(!$saved){ $saved = 'Failed to Save Venue'. $venue; Log::info($saved); } return $saved;
  • 下面我已经回答了 3 个想法 :),希望其中一个能帮助您解决问题。
  • 我确实这么认为。可能你应该尝试调试$saved 而不是$venue。或者在保存之前转储$venue

标签: php laravel unit-testing laravel-5 phpunit


【解决方案1】:

您可以按照the docs: 在单元测试中模拟 Log 外观,如下所示

public function test_venue_store_failed(){
    $venue = new Venue();

    Log::shouldReceive('info')
        ->with('Failed to Save Venue'. $venue);

    $venueRepo = new VenueRepository();
    $this->withExceptionHandling();
    $venueRepo->store($venue);
}

【讨论】:

    【解决方案2】:

    也许您可以在模型上使用事件监听器。 使用它,您可以获得有关创建或其他事件的日志。 查看下面的示例。 希望有所帮助。

    信息 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');
                });
    
            }
    
        }
    

    信息 2。

    模型上还有一个exists方法

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

    信息 3

    要在$venue-&gt;save(); 错误时获取插入查询,您可以尝试像这样捕获异常:

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

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-03
      • 2017-10-26
      • 1970-01-01
      • 2019-03-25
      • 2011-06-30
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      相关资源
      最近更新 更多