【问题标题】:Laravel user hierarchy w/ relationship unit testing gone wrong带有关系单元测试的 Laravel 用户层次结构出错了
【发布时间】:2021-08-15 00:35:03
【问题描述】:

场景: 因此,我有一个 users 表,其中包含一个名为 parent_id 的 ForeignKey,它引用了 users 表的 id。这允许一个用户属于另一个用户,并且一个用户有许多“子”用户(一对多)。

现在,问题本身是由于单元测试。当我使用数据库中的记录时,它按预期工作,但模拟关系值似乎不起作用。另请注意,对数据库运行此测试没有意义,因为该结构具有很多依赖项。

目标:在不访问数据库的情况下测试规则

规则:

<?php

namespace App\Rules;

use App\Repositories\UserRepository;
use Illuminate\Contracts\Validation\Rule;

class UserHierarchy implements Rule
{
    /**
     * User related repository
     *
     * @var \App\Repositories\UserRepository $userRepository
     */
    private $userRepository;

    /**
     * User to affected
     *
     * @var null|int $userId 
     */
    private $userId;

    /**
     * Automatic dependency injection
     *
     * @param \App\Repositories\UserRepository $userRepository
     * @param integer|null $userId
     */
    public function __construct(UserRepository $userRepository, ?int $userId)
    {
        $this->userRepository = $userRepository;
        $this->userId = $userId;
    }

    /**
     * Determine if the validation rule passes.
     * Uses recursivity in order to validate if there is it causes an infinite loop
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        if (is_null($value)) {
            return true;
        }

        $childrenOfUserToBeUpdated = $this->userRepository->show($this->userId);
    //pluck_key_recursive is a customized function but its not posted because the issue can be traced on the dd below
        $notAllowedUserIds = pluck_key_recursive($childrenOfUserToBeUpdated->childrenTree->toArray(), 'children_tree', 'id');
         dd($childrenOfUserToBeUpdated->childrenTree->toArray());
        return in_array($value, $notAllowedUserIds) ? false : true;
    }
}

用户关系如下:

/**
     * An User can have multiple children User
     *
     * @return EloquentRelationship
     */
    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

    /**
     * An User can have a hierarchal of children
     *
     * @return EloquentRelationship
     */
    public function childrenTree(): HasMany
    {
        return $this->children()->with('childrenTree');
    }

这是测试:

<?php

namespace Tests\Unit\Rules;

use App\Repositories\UserRepository;
use App\Rules\UserHierarchy;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Mockery;
use Tests\TestCase;

class UserHierarchyTest extends TestCase
{
    /**
     * Setting up Mockery
     *
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();
           $this->parent = new User(['id' => 1]);
        $this->sonOne = new User(['id' => 2, 'parent_id' => $this->parent->id]);
        $this->sonTwo = new User(['id' => 3, 'parent_id' => $this->parent->id]);
        $this->sonThree = new User(['id' => 4, 'parent_id' => $this->parent->id]);
        $this->grandSonOne = new User(['id' => 5, 'parent_id' => $this->sonOne->id]);
        $this->grandSonTwo = new User(['id' => 6, 'parent_id' => $this->sonOne->id]);

 //$this->sonOne->children = new Collection([$this->grandSonOne, $this->grandSonTwo]);
        //$this->parent->children = new Collection([$this->sonOne, $this->sonTwo, $this->sonThree]);
        $this->sonOne->childrenTree = new Collection([$this->grandSonOne, $this->grandSonTwo]);
        $this->parent->childrenTree = new Collection([$this->sonOne, $this->sonTwo, $this->sonThree]);


        $this->userRepositoryMock = Mockery::mock(UserRepository::class);
        $this->app->instance(UserRepository::class, $this->userRepositoryMock);
    }

    /**
     * The rule should pass if the user to be updated will have not a child as a parent (infinite loop)
     *
     * @return void
     */
    public function test_true_if_the_user_id_isnt_in_the_hierarchy()
    {
        //Arrange
        $this->userRepositoryMock->shouldReceive('show')->once()->with($this->parent->id)->andReturn($this->parent);
        //Act
        $validator = validator(['parent_id' => $this->randomUserSon->id], ['parent_id' => resolve(UserHierarchy::class, ['userId' => $this->parent->id])]);
        //Assert
        $this->assertTrue($validator->passes());
    }

    /**
     * The rule shouldnt pass if the user to be updated will have a child as a parent (infinite loop)
     *
     * @return void
     */
    public function test_fail_if_the_user_id_is_his_son_or_below()
    {
        //Arrange
        $this->userRepositoryMock->shouldReceive('show')->once()->with($this->parent->id)->andReturn($this->parent);
        //Act
        $validator = validator(['parent_id' => $this->grandSonOne->id], ['parent_id' => resolve(UserHierarchy::class, ['userId' => $this->parent->id])]);
        //Assert
        $this->assertFalse($validator->passes());
    }

    /**
     * Tear down Mockery
     *
     * @return void
     */
    public function tearDown(): void
    {
        parent::tearDown();
        Mockery::close();
    }
}

我尝试了很多组合,但我似乎无法让它发挥作用。我什至尝试一直模拟用户模型,但结果相同:用户的子代被转换为数组,但孙代仍作为集合的项目对象。

这是该测试的示例输出:

array:3 [
  0 => array:6 [
    "name" => "asd"
    "email" => "asdasdasd"
    "id" => 2
    "parent_id" => 1
    "childrenTree" => Illuminate\Database\Eloquent\Collection^ {#898
      #items: array:2 [
        0 => App\Models\User^ {#915
          #fillable: array:8 [...

为什么 ->toArray() 将所有内容都转换为具有真实数据库对象的数组,但在设置预期结果时却没有?

【问题讨论】:

  • 我刚刚注意到,在单元测试和 app-> 实例中,我实际上并不需要解析助手,但可以稍后进行优化。
  • 在您的$this-&gt;parent = new User(['id' =&gt; 1]); 行之后,放置一个dd($this-&gt;parent-&gt;id)。我有预感你会得到null,因为属性是guarded。而且由于记录永远不会是save()ed,因此 AI 索引也不会帮助您。
  • 属性 id 在填充物上,它显示。问题是,如果我设置 $this->user->children = something,那么每当我检索关系子项时,它都会返回分配的值,因为 eloquent 仅在它还没有分配值的情况下从数据库中获取。我可以使用当前 DD 查看所有 id,问题是它不会在应该将项目对象转换为数组时
  • 首先,不要在 Laravel 中使用 Repository 模式,它是一种反模式,google 更多关于它的信息。其次,您不需要模拟关系船...使用工厂创建“模拟”用户和所有东西,但是在测试框架时您的测试毫无意义(您正在测试关系是否有效)。所以,你的测试没有意义。如果您编写您希望测试的内容,我可以为您提供帮助。

标签: laravel eloquent phpunit laravel-8 eloquent-relationship


【解决方案1】:

我想你可能只是在寻找$parentModel-&gt;setRelation($name, $modelOrEloquentCollection)。如果您实际上并未将记录保存到数据库,即使 ID 值匹配,Eloquent 也不会为您连接它们。

【讨论】:

  • 这行得通,谢谢!我不知道 setRelation 方法,但这以某种方式正确地将值设置为关系,而不是按照我的做法,现在它将集合转换为数组。据我所知,eloquent 的工作方式是,它仅在未填充属性时才获取新数据(在谈论关系时,调用 ->children 正在使用称为 children 的函数的值设置 children 属性)
  • 乐于助人。抱歉,我之前让你叫错了树。直到我阅读了您关于它与您明确设置的数据正常运行的评论时,它才单击。然后我想起来了,人际关系也是如此。请注意您的关系类型。如果它是一对多的,您将不得不手动实例化您自己的 Eloquent/Collection 并将其用作关系,而不仅仅是其中的模型。
  • 可能我解释得不好,抱歉!我正在尝试优化正在进行的测试,一些较旧的项目每次测试需要 1-5 秒,具体取决于测试某些方面的复杂性以及诸如规则、门、策略之类的东西,对我来说访问数据库没有意义(除了少数情况)何时可以模拟依赖项并提供更清晰、可维护和更快的测试结果。还有很长的路要走,但这肯定会有助于体验(好或坏,让我们找出答案)。祝你有美好的一天!
猜你喜欢
  • 2016-03-18
  • 1970-01-01
  • 2018-09-08
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 2014-07-08
  • 2019-12-11
相关资源
最近更新 更多