本文介绍了PHPUnit-Symfony2:方法应被调用1次,实际上被调用0次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在和Mock一样苦苦挣扎.我尝试在我的网站(Symfony2)上进行一些测试.这是我的错误:

I am struggling so much with Mock. I try to do some tests on my website (Symfony2).Here is my error :

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参数的示例,例如该类的一个属性(但是我现在没有时间更改它了).我希望这不是问题的根源...这是我的代码:

I saw few examples on the internet with the argument $entityManager like an attribute of the class (but I have no time to change it anymore). I hope it's not the origin of the problem... Here is my code :

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));
    }
}

有人有想法吗?谢谢!

推荐答案

问题在以下行部分中:

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

通过声明->expects($this->once()),您表示此方法在每个测试用例中均被调用一次.但是,如果您不使用它,它将触发异常.

By declaring ->expects($this->once()) you say that this method is called once per test case. But if you don't use it, it will trigger an exception.

如果您不需要每次测试精确触发一次方法,请改用->expects($this->any()).

If you don't need the method to be triggered excactly once per test, use ->expects($this->any()) instead.

这篇关于PHPUnit-Symfony2:方法应被调用1次,实际上被调用0次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:16