如何在Symfony中测试持久集合的大小?

问题描述 投票:-1回答:1

Symfony 5.0.5。我通过这种方法提供服务:

public function getFleas(Cat $cat): Collection
{
    return $cat->getFleas();
}

在我的Cat实体中:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Flea", mappedBy="cat")
 */
private $fleas;

我正在尝试为getFleas方法编写测试:

public function testItReturnsAListOfFleas()
{
    $cat = $this->createCat();
    $fleaList = [];
    $numFleas = 5;
    for ($i = 0; $i < $numFleas; $i++) {
        $fleaList[] = $this->createFlea($cat);
    }
    $fleas = $this->fleaService->getFleas($cat);
    $this->assertCount($numFleas, $fleas);
}

private function createCat(): Cat
{
    $cat = new Cat();
    $cat->setName('John');
    $this->em->persist($cat);
    $this->em->flush();
    return $cat;
}

private function createFlea(Cat $cat): Flea
{
    $flea = new Flea();
    $flea->setName('Nigel');
    $flea->setCat($cat);
    $this->em->persist($flea);
    $this->em->flush();
    return $flea;
}

但是,这失败了。 $fleas返回的getFleas持久性集合的计数始终为0。如何获得$fleas的数量?我也尝试过

$this->assertSame($numFleas, $fleas->count());

但是这也会返回0

php testing doctrine
1个回答
0
投票

您需要在您的addFlea(Flea)类中添加Cat方法,并且每次创建一个新的Flea时,都要调用它。

基本上,在Cat上:

public function addFlea(Flea $flea) {
   if (!$this->fleas->contains($flea))      {
     $this->fleas->add($flea);
   }
}

并修改Flea::setCat(Cat)

public function setCat(Cat $cat)
{
     $cat->addFlea($this);
     $this->cat = $cat;

}

对不起错字。在手机上键入代码不容易。自动更正不喜欢PHP。

© www.soinside.com 2019 - 2024. All rights reserved.