如何为模型编写单元测试有附加 属性

How to write a unit test for model have appends property

我有模型产品,它具有受保护的 属性 $appends = ['avg_rating']。此平均评分由 getAvgRatingAttribute() 函数设置。我想为模型产品中的附加 属性 编写单元测试,有什么想法吗?

class Product extends Model
{
    protected $appends = [
        'avg_rating',
    ];
    
    public function getAvgRatingAttribute()
    {
        return $this->comments()->avg('rating');
    }
}

I want to test the model has the appended property and it's returning the correct avg. Do you have any idea?

//use Tests\TestCase;
public function test_your_test_name(){
 $post = Post::create([]);
 $post->comments()->saveMany([
   new Comment(['rating' => 2]),
   new Comment(['rating' => 4]),
   new Comment(['rating' => 1]),
  ]);

 $this->assertTrue(isset($post->avg_rating)); //to test if attribute is set
 $this->assertEquals(  (2+4+1)/3, $post->avg_rating ); //test if avg rating is correct
}

我可能没有抓住要点,但是,我应该说这些测试似乎是不必要的。这与测试 getAvgRatingAttribute 是否设置了属性以及 avg 函数是否 returns 正确的平均值相同,框架已经测试过。