2018-07-09 13:06
浏览 76


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.


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

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




下面的代码显示了商店功能。 “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.

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

    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:

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

相关推荐 更多相似问题