Laravel测试用例错误-调用null上的成员函数where()



我已经在ModelClass 中定义了关系

public function allocations(): MorphMany
{        
return $this->morphMany(
Allocation::class,
'allocatable',
'ref_class',
'ref_id'
)->where('is_active', 1); // this line is creating issue
}

测试用例

public function testAllocations(): void
{
// Arrange
$morphMany = $this->partialMock(MorphMany::class);
$model = $this->createPartialMock(
ModelClass::class,
['morphMany']
);
// Expectations
$model->expects($this->once())
->method('morphMany')
->with(
Allocation::class,
'allocatable',
'ref_class',
'ref_id'
)
->willReturn($morphMany);
// Action
$result = $model->allocations();
// Assert
$this->assertInstanceOf(MorphMany::class, $result);
}

错误:调用空上的成员函数where((

如果我删除关系中的where条件,则测试正确通过。我需要关系中的条件。如何在TestCase中传递where条件?

任何建议都很好。谢谢:(

你试过这样的东西吗?

$data = $this->morphMany(
Allocation::class,
'allocatable',
'ref_class',
'ref_id'
);
return $data->where('is_active', 1);

最新更新