【发布时间】:2021-06-30 07:39:38
【问题描述】:
我有一个带有 User 实体的 Symfony 应用程序,该实体与 Cat 实体具有多对多关系。我还有一个 PhpUnit 测试,它检查从 1 个用户删除一只猫(属于 2 个用户)实际上并没有删除猫:
public function testDeletingACatBelongingToTwoUsersOnlyDeletesTheAssociationNotTheCat()
{
$cat = $this->createCat();
// Associate with user 1
$user1 = new User();
$user1->setEmail('test@example.com');
$user1->setPassword('pwdpwd');
$user1->addCat($cat);
$this->em->persist($user1);
// Associate with user 2
$user2 = new User();
$user2->setEmail('another@example.com');
$user2->setPassword('pwdpwd');
$user2->addCat($cat);
$this->em->persist($user2);
$this->em->flush();
// Sanity check:
$this->assertCount(1, $user1->getCats()); // PASS
$this->assertCount(1, $user2->getCats()); // PASS
$this->assertCount(2, $cat->getUsers()); // FAIL (0)
// ... perform the test (not shown here)
}
private function createCat(): Cat
{
$cat = new Cat();
$cat->setName($this->name);
$this->em->persist($cat);
$this->em->flush();
return $cat;
}
我的问题是,为什么$cat->getUsers() 在我的测试中返回0?在运行时它不会,它返回正确的值。只有在测试中才会返回0。
以下是我的实体的相关摘录,由 Symfony 自动生成:
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* @ORM\ManyToMany(targetEntity=Cat::class, inversedBy="users")
*/
private $cats;
/**
* @return Collection|Cat[]
*/
public function getCats(): Collection
{
return $this->cats;
}
public function addCat(Cat $cat): self
{
if (!$this->cats->contains($cat)) {
$this->cats[] = $cat;
}
return $this;
}
public function removeCat(Cat $cat): self
{
$this->cats->removeElement($cat);
return $this;
}
}
/**
* @ORM\Entity(repositoryClass=CatRepository::class)
*/
class Cat
{
/**
* @ORM\ManyToMany(targetEntity=User::class, mappedBy="cats")
*/
private $users;
/**
* @return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
}
【问题讨论】:
-
我们通常只使用Mockery 来处理类似的事情。您可以根据需要模拟 EntityManager 并让它返回您需要的内容。这样你是在测试你的实际逻辑,而不是 EM 本身。
标签: php symfony doctrine-orm phpunit