简体   繁体   English

如何在聚合根中测试生成的 id

[英]How to test generated id in aggregate root

I wanna to test my entities created from doctrine, but i don`t know how to test id if they are generated themself while object save to database.我想测试从 doctrine 创建的实体,但我不知道如何在id保存到数据库时测试它们是否是自己生成的。

class Dish
{
    private ?int $id;

    private Collection $prices;

    public function __construct()
    {
        $this->prices = new ArrayCollection();
    }

    public function identifier(): string
    {
        return $this->id;
    }

    public function isEquals(Dish $dish): bool
    {
        return $this->identifier() === $dish->identifier();
    }

    public function addPrice(float $price)
    {
        $this->prices->add(new DishPrice($this, $price));
    }
}
class DishPrice
{
    use DeletedEntityTrait;

    private ?int $id;
    private float $price;

    private Dish $dish;

    public function __construct(Dish $dish, float $price)
    {
        $this->dish = $dish;
        $this->price = $price;
    }

    public function identifier(): string
    {
        return $this->id;
    }

    public function isEquals(Dish $dish): bool
    {
        return $this->identifier() === $dish->identifier();
    }
}

How to test isEquals methods in both classes?如何在两个类中测试isEquals方法?

Basically you have two options.基本上你有两个选择。

First option is functional test.第一个选项是功能测试。 You can create two entities and persist them to the database.您可以创建两个实体并将它们持久保存到数据库中。

Second option is pass ID to the constructor.第二个选项是将 ID 传递给构造函数。 To be able to do this you can add method to repository that will provide you next ID for your entity in service layer:为了能够做到这一点,您可以向存储库添加方法,该方法将为您在服务层中的实体提供下一个 ID:

interface DishRepository
{
    public function getNextIdentity(): int;
}

$id = $repository->getNextIdentity();
$dish = new Dish($id);

and in unit-tests you can pass to the constructor whatever ID that you want在单元测试中,您可以将所需的任何 ID 传递给构造函数

$testId = 111;
$dish = new Dish($testId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM