PHPUnit - Symfony2:方法被调用1次,实际上被调用0次

时间:2015-05-14 17:56:00

标签: symfony phpunit

我和Mock一起苦苦挣扎。我尝试在我的网站(Symfony2)上做一些测试。 这是我的错误:

There was 1 failure:

1) L3L2\EntraideBundle\Tests\Controller\InboxControllerTest::testGetNbTotalMessagePasDejaVu
Expectation failed for method name is equal to <string:getNbTotalMessagePasDejaVu> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

我在互联网上看到几个例子,其中$ entityManager是类的一个属性(但我没有时间再改变它了)。我希望它不是问题的根源...... 这是我的代码:

InboxController:

public function getNbTotalMessagePasDejaVu(ObjectManager $entityManager = null)
{
    if($entityManager == null)
        $entityManager = $this->getDoctrine()->getEntityManager();

    $repository = $entityManager->getRepository('L3L2EntraideBundle:Message');

    $nbMessagePasDejaVu = $repository->getNbTotalMessagePasDejaVu(1);       //change 1 to $this->getUser()->getId()

    return $nbMessagePasDejaVu;
}

InboxControllerTest:

class InboxControllerTest extends \PHPUnit_Framework_TestCase
{
    public function testGetNbTotalMessagePasDejaVu()
    {
        $msgRepository = $this
            ->getMockBuilder("\Doctrine\ORM\EntityRepository")
            ->disableOriginalConstructor()
            ->getMock();

        $msgRepository->expects($this->once())
            ->method('getNbTotalMessagePasDejaVu')
            ->will($this->returnValue(0));


        $entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
            ->disableOriginalConstructor()
            ->getMock();
        $entityManager->expects($this->once())
            ->method('getRepository')
            ->will($this->returnValue($msgRepository));

        $msg = new InboxController();

        $this->assertEquals(0, $msg->getNbTotalMessagePasDejaVu($entityManager));
    }
}

有没有人有想法?谢谢!

2 个答案:

答案 0 :(得分:2)

问题出在以下行部分:

$msgRepository->expects($this->once())
    ->method('getNbTotalMessagePasDejaVu')
    ->will($this->returnValue(0));

通过声明->expects($this->once()),您说每个测试用例都会调用一次此方法。但是如果你不使用它,它将触发异常。

如果您不需要在每次测试时准确触发该方法,请改用->expects($this->any())

答案 1 :(得分:1)

如果你只想存根方法并让它返回一些你可以做你已经拥有的东西。但是如果想要验证该方法是否实际被调用,则必须“模拟”#39;它。这是setMethods()方法的用途。

$entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
            ->disableOriginalConstructor()
            ->setMethods(array('getRepository'))
            ->getMock();

现在你可以说->expects($this->once())->method('getRepository')