Codeception\Util\Stub methods ::exactly and ::once don't work Codeception\Util\Stub methods ::exactly and ::once don't work php php

Codeception\Util\Stub methods ::exactly and ::once don't work


You need to pass $this as a third parameter to makeEmpty:

$stub = StubUtil::makeEmpty('myClass', [    'myMethod' => StubUtil::exactly(2, function () { return 'returnValue'; })], $this);


Instead of use \Codeception\Util\Stub to Expected::once(), modify your unit tests to extends \Codeception\Test\Unit then use $this->make() or $this->makeEmpty() to create your stubs. It will works as you expect ;)

For example:

class MyProcessorTest extends \Codeception\Test\Unit {    public function testSomething()    {        $processor = new MyProcessor(            $this->makeEmpty(EntityManagerInterface::class, [                'remove' => Expected::never(),                'persist' => Expected::once(),                'flush' => Expected::once(),            ])        );        $something = $this->somethingFactory(Processor::OPERATION_CREATE);        $processor->process($something);    }}

Cheers!


Looks like your method does not exist in the target class that you mock.

If the method exists then Codeception replaces it with the stub you provide. And if this method does not exist then Codeception adds a field with this name to the stub object.

It is because methods and properties are passed in the same array so Codeception has no other way to tell methods from properties.

So first create a method myMethod in your class myClass.