Reputation: 67
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.
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));
}
}
Does anyone have an idea ? Thank you !
Upvotes: 0
Views: 3220
Reputation: 3967
If you only want to stub the method and make it return something you can do what you already have. But if want to verify that the method was actually called you have to 'mock' it. This is what setMethods()
method is for.
$entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
->disableOriginalConstructor()
->setMethods(array('getRepository'))
->getMock();
Now you can say ->expects($this->once())->method('getRepository')
.
Upvotes: 1
Reputation: 13107
The problem is in the following line section:
$msgRepository->expects($this->once())
->method('getNbTotalMessagePasDejaVu')
->will($this->returnValue(0));
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.
If you don't need the method to be triggered excactly once per test, use ->expects($this->any())
instead.
Upvotes: 2