Calling a method of a mock object

53 views Asked by At

I am testing a service with PHPUnit.

I am using setUp() to create mock objects of the dependencies that my service accepts, like this:

 public function setUp()
    {
        $this->fooManagerMock = $this->getFooManagerMock();
        $this->barManagerMock = $this->getBarManagerMock();
        $this->treeManagerMock = $this->getTreeManagerMock();
        $this->loggerMock = $this->getLoggerMock();

     $this->myService = new MyService($this->fooManagerMock, $this->barManagerMock, $this->treeManagerMock, $this->loggerMock);
    }

Bundle\Tests\Service\MyTest::testServiceWithValidData

   /**
     * @dataProvider getServiceValidCaseData
     */
    public function testServiceWithValidData($case)
    {
         $this->assertTrue($this->myService->serve($fooArray));
    }

It turns out that a entity manager that in my serve() function, I am having something like this:

return $this->fooManager->find($fooId) !== null;

in this case $this->fooManager is instance of Mock_FooManager_4038382a and the whole test fails.

Any suggestions are more than welcome.

UPDATE

/**
     * @return \PHPUnit_Framework_MockObject_MockBuilder
     */
    private function getFooManagerMock()
    {
        return $this->getMockBuilder(
            '\MyBundle\Entity\Manager\FooManager'
        )->disableOriginalConstructor()->getMock();
    }

Example for @matteo

I was expecting $fooManager->find($id) to return me a specific instance of Foo, such as:

\MyBundle\Manager\FooManager{
"id" : 234234,
"status" : "pending".
"color" : "yellow",
"tree" : [
         "id" : 2345,
         "height" :160
       ]
}
1

There are 1 answers

10
Matteo On

You must specify in the test case which behaviour the mocked entity must do, try adding this code in the testServiceWithValidData method, before call the tested service:

       $fooMockObj = $this->getMock('\MyBundle\Entity\Foo');
       // Eventually mock some method
       // PS You can return a concrete instance too
       // $fooMockObj= new  \MyBundle\Entity\Foo();

        $this->fooManager
            ->expects($this->any())
            ->method('find')
//            ->with($anOptionalInputId)
             ->will($this->returnValue($fooMockObj));

Hope this help