0

it seems this mock doesn't work and I can't understand why. To me it's due to the new class

The class I'm testing:

class someClass
{
    public function run()
    {
        $anotherClass = new AnotherClass($params);
        // more code here ... 
    }
}

The AnotherClass class:

class AnotherClass
{
    public function __construct($params) {
         // more code here, not important ...
    }
    
    public function myMethod($data): bool
    {
        // more code here not important ...

        return $aBooleanVariable; 
    }
}

In my someClassTest.php I have setup a mock for AnotherClass like that:

$anotherClassMock = $this->getMockBuilder(AnotherClass::class)
    ->onlyMethods(['myMethod'])
    ->setConstructorArgs($params)
    ->getMock();

$anotherClassMock->method('myMethod')
    ->with($data)
    ->willReturn(true);

\Yii::$container->set(AnotherClass::class, $anotherClassMock);

Last line it's because I'm using Yii framework.

It seems the mock doesn't work because it will never return true. What am I doing wrong?

Alberto Ar3s
  • 311
  • 1
  • 3
  • 14
  • Does this answer your question? [Phpunit: replace class with mock](https://stackoverflow.com/questions/40915746/phpunit-replace-class-with-mock) – Michal Hynčica Aug 09 '22 at 14:09
  • Besides ways mentioned in linked question. The [mockery library](http://docs.mockery.io/en/latest/cookbook/mocking_hard_dependencies.html) also have a way to mock these. The problem is that it's done by creating mocked class definition before its loaded by autoloader. But once the class is defined it cannot be unloaded and because of that it can create issues when running multiple test cases at once. – Michal Hynčica Aug 09 '22 at 14:28

0 Answers0