【问题标题】:Laravel Test Case Error - Call to a member function where() on nullLaravel 测试用例错误 - 在 null 上调用成员函数 where()
【发布时间】:2021-09-08 10:06:29
【问题描述】:

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

错误:在 null 上调用成员函数 where()

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

任何建议都会很棒。谢谢:)

【问题讨论】:

    标签: laravel unit-testing laravel-8 laravel-testing


    【解决方案1】:

    你尝试过这样的事情吗?

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

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2018-09-06
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2019-08-21
      • 1970-01-01
      • 2017-07-19
      相关资源
      最近更新 更多