作者:初来乍到1231 | 来源:互联网 | 2023-05-25 18:21
我想第一次使用Prophecy("phpspec/prophecy-phpunit")为我的类创建单元测试.我想测试一个在同一个服务中调用另一个函数的函数,这里是代码:
class UserManager
{
private $em;
private $passwordHelper;
public function __construct(\Doctrine\ORM\EntityManager $em, \MainBundle\Helper\PasswordHelper $passwordHelper)
{
$this->em = $em;
$this->passwordHelper = $passwordHelper;
}
public function getUserForLdapLogin($ldapUser)
{
$dbUser = $this
->em
->getRepository('MainBundle:User')
->findOneBy(array('username' => $ldapUser->getUsername()));
return (!$dbUser) ?
$this->createUserFromLdap($ldapUser) :
$this->updateUserFromLdap($ldapUser, $dbUser);
}
我遇到的第一个问题是我正在使用findOneByUsername
和预言,据我所知,不允许你:模拟魔术方法(_call
for EntityRepository
),不存在的模拟方法,模拟你正在测试的类.如果这些都是真的我有点腌渍,这意味着我不能测试这个函数而不测试类中的其他函数.
到目前为止,我的测试看起来像这样:
class UserManagerTest extends \Prophecy\PhpUnit\ProphecyTestCase
{
public function testGetUserForLdapLoginWithNoUser()
{
$ldapUser = new LdapUser();
$ldapUser->setUsername('username');
$em = $this->prophesize('Doctrine\ORM\EntityManager');
$passwordHelper = $this->prophesize('MainBundle\Helper\PasswordHelper');
$repository = $this->prophesize('Doctrine\ORM\EntityRepository');
$em->getRepository('MainBundle:User')->willReturn($repository);
$repository->findOneBy(array('username' => 'username'))->willReturn(null);
$em->getRepository('MainBundle:User')->shouldBeCalled();
$repository->findOneBy(array('username' => 'username'))->shouldBeCalled();
$service = $this->prophesize('MainBundle\Helper\UserManager')
->willBeConstructedWith(array($em->reveal(), $passwordHelper->reveal()));
$service->reveal();
$service->getUserForLdapLogin($ldapUser);
}
}
当然,测试失败是因为承诺$em
和存储库未得到满足.如果我实例化我正在测试的类,测试将失败,因为该函数然后调用createUserFromLdap()
同一个类并且未经过测试.
有什么建议?