【问题标题】:mocking an Eloquent collection嘲笑 Eloquent 集合
【发布时间】:2019-03-10 01:42:28
【问题描述】:

我想,疯狂地解释原因,创建一个模拟 Eloquent 集合

我试过这个:

        $collection = new \Illuminate\Database\Eloquent\Collection(
            array(
                new User( array( "id" => 1 ) ),
                new User( array( "id" => 2 ) ),
                new User( array( "id" => 3 ) ),
                new User( array( "id" => 4 ) ),
                new User( array( "id" => 5 ) )
            )
        );

        $collection->get(); // Fails

但事实证明,这个集合没有 ->get() 方法,就像你通常做的那样,比如:

User::take( 2 )->get();

这最终是因为 \Illuminate\Database\Eloquent\Collection 只是一个命名空间并使用了 \Illuminate\Database\Collection

任何想法如何模拟实际正常工作的 Eloquent 集合?

【问题讨论】:

  • 集合中没有get。这是一个Query\Builder 方法,通过Eloquent\Builder (在您的示例中通过User 模型)调用。在这种情况下,收集是 get 调用的结果。原始Query\Builder 将返回一个数组。

标签: php unit-testing laravel eloquent


【解决方案1】:

我发现你可以选择你想要创建的模型类型并在上面调用newCollection

$collection = new \User();
$collection->newCollection(
    array(
        new User( array( "id" => 1 ) ),
        new User( array( "id" => 2 ) ),
        new User( array( "id" => 3 ) ),
        new User( array( "id" => 4 ) ),
        new User( array( "id" => 5 ) )
    )
);

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_newCollection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 2016-10-02
    • 2019-12-20
    • 1970-01-01
    • 2019-02-15
    • 2010-09-23
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多