如何使用Prophecy来测试您正在测试的类中的方法?

ale*_*dra 6 php phpunit symfony prophecy

我想第一次使用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);
     }
Run Code Online (Sandbox Code Playgroud)

我遇到的第一个问题是我正在使用findOneByUsername和预言,据我所知,不允许你:模拟魔术方法(_callfor 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);
     }
}
Run Code Online (Sandbox Code Playgroud)

当然,测试失败是因为承诺$em和存储库未得到满足.如果我实例化我正在测试的类,测试将失败,因为该函数然后调用createUserFromLdap()同一个类并且未经过测试.

有什么建议?

Ban*_*ang 1

第一个问题:

不要使用魔法,魔法是邪恶的。__call 可能会导致不可预测的行为。

“$em 和存储库上的承诺没有兑现”:

不要让你的代码依赖于类而是接口。然后模拟接口而不是类!您应该模拟 ObjectManager 而不是 EntityManager。(不要忘记更改参数的类型)

最后一点:

揭晓之前。

$service->createUserFromLdap()
   ->shouldBeCalled()
   ->willReturn(null);
Run Code Online (Sandbox Code Playgroud)