Home > OS >  Why I am unable to assert that method has been called on my mocked service?
Why I am unable to assert that method has been called on my mocked service?

Time:01-31

I have made a simple class named MyService

namespace App\Services;

class MyService
{

    private $anotherService;

    public function setService(AnotherService $anotherService)
    {
        $this->anotherService = $anotherService;
    }

    public function getService()
    {
        if(empty($this->anotherService)){
            $this->setService(new AnotherService());
        }

        return $this->anotherService;
    }

    public function call()
    {
        $anotherService = $this->getService();

        $anotherService->SetXY(5,10);
    }
}

As you can se via a setter I set as Depedency the AnotherService:

namespace App\Services;

class AnotherService
{
    public function SetXY($x,$y)
    {

    }
} 

In order to test whether the MyService runs as expected I made the following test:

namespace Tests\Services;

namespace Tests\Services;

use App\Services\MyService;
use App\Services\AnotherService;

use PHPUnit\Framework\TestCase;
use Mockery;

class MyServiceTest extends TestCase
{

    public function testService()
    {
        $mockedAnotherService = Mockery::spy(AnotherService::class);
        $mockedAnotherService->shouldReceive('SetXY');

        $service = new MyService();
        $service->setService($mockedAnotherService);
        $service->call();

        $mockedAnotherService->shouldHaveReceived()->setXY(5,10);
    }
}

But for some reason seems that I am unable to assert that setXY is called despite the opposite. The error is:

1) Tests\Services\MyServiceTest::testService
Mockery\Exception\InvalidCountException: Method setXY(<Any Arguments>) from Mockery_0_App_Services_AnotherService should be called
 at least 1 times but called 0 times.

/var/www/html/api/vendor/mockery/mockery/library/Mockery/CountValidator/AtLeast.php:47
/var/www/html/api/vendor/mockery/mockery/library/Mockery/Expectation.php:310
/var/www/html/api/vendor/mockery/mockery/library/Mockery/ReceivedMethodCalls.php:46
/var/www/html/api/vendor/mockery/mockery/library/Mockery/VerificationDirector.php:36
/var/www/html/api/vendor/mockery/mockery/library/Mockery/HigherOrderMessage.php:46
/var/www/html/api/tests/Services/MyServiceTest.php:23
phpvfscomposer:///var/www/html/api/vendor/phpunit/phpunit/phpunit:60


Do you know why that does happen?

CodePudding user response:

There is a typo in: $mockedAnotherService->shouldHaveReceived()->setXY(5,10);

Should be: $mockedAnotherService->shouldHaveReceived()->SetXY(5,10);

  • Related