0

有什么方法可以完全测试这种方法,因为我没有将模型直接传递给它,而是希望我的经理为我创建它?

public function giveAchievement(User $user, $achievementType)
{
    $a2p = new Achievement2User();
    $a2p->setUser($user);
    $a2p->setAchievement($this->em->getReference(AchievementManager::ACHIEVEMENT_CLASS, $achievementType));
    $a2p->setObtainedOn(new \DateTime());

    $this->em->persist($a2u);
    $this->em->flush();
}

因为我嘲笑$em了,我可以检查它的persist方法是否被实例调用Achievement2User

$this->em->expects($this->once())
    ->method('persist')
    ->with($this->isInstanceOf('Achievement2User'));

但是有什么方法可以实际检查传递的模型是否正确设置了Userand字段?Achievement

4

1 回答 1

0

这是我设法做到的:

// Create $userObject and $achievementObject entities/models

$this->em->expects($this->once())
    ->method('persist')
    ->with($this->isInstanceOf('Achievement2User'))
    ->will($this->returnCallback(function (Achievement2User $a2u) use ($userObject, $achievementObject) {
        $this->assertTrue($a2u === $userObject);
        $this->assertTrue($a2u === $achievementObject);
    }));

PHPUnit 显然会将预期的方法参数传递给回调函数。

于 2014-03-30T16:30:15.443 回答