【问题标题】:PHPUnit - Symfony2 : Method was expected to be called 1 times, actually called 0 timesPHPUnit - Symfony2:方法预期被调用 1 次,实际上被调用 0 次
【发布时间】:2015-05-21 19:05:36
【问题描述】:

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

收件箱控制器:

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

有人有想法吗?谢谢!

【问题讨论】:

  • 你的单元测试中有合适的使用语句吗?如果 InboxController 与您预期的不同,则可能会导致这样的症状。

标签: symfony phpunit


【解决方案1】:

问题出在以下行部分:

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

通过声明-&gt;expects($this-&gt;once()),您表示该方法在每个测试用例中调用一次。但是不使用就会触发异常。

如果您不需要每次测试只触发一次该方法,请改用-&gt;expects($this-&gt;any())

【讨论】:

    【解决方案2】:

    如果您只想对方法进行存根并使其返回某些内容,则可以执行已有的操作。但是,如果要验证该方法是否被实际调用,则必须“模拟”它。这就是 setMethods() 方法的用途。

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

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

    【讨论】:

    • 如果你能写一个关于添加setMethods参数的句子就好了。
    猜你喜欢
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2020-09-15
    • 2017-01-03
    • 2018-11-14
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多