phpunit icon indicating copy to clipboard operation
phpunit copied to clipboard

Is not possible mock method called in constructor

Open leandrogehlen opened this issue 2 years ago • 3 comments

Q A
PHPUnit version 9.5.21
PHP version 8.1.2
Installation Method Composer

Summary

Is not possible mock method in constructor

Current behavior

Mocking method result called in constructor always return null instead of what was defined in mock.

How to reproduce

(https://github.com/leandrogehlen/mock-method-constructor)

Expected behavior

Mocking method result called in constructor should return what was defined in willReturn method.

leandrogehlen avatar Jul 06 '22 11:07 leandrogehlen

I do not understand what you are trying to report.

sebastianbergmann avatar Jul 06 '22 12:07 sebastianbergmann

https://github.com/leandrogehlen/mock-method-constructor/blob/master/tests/SomeClassTest.php#L24

Should return

object(stdClass)#369 (1) {
  ["name"]=>
  string(4) "Bill"
}

but is returning null

leandrogehlen avatar Jul 06 '22 12:07 leandrogehlen

I'm very confused what you are trying to test. It seems like your method is returning a fixed empty object.

protected function createObject()
{
    return new stdClass();
}

So your test should be something like this:


$object = new SomeClass();

$this->assertEquals(
    new \StdClass(),
    $object->getObject()
);

You are instead trying to mock the class you are testing to return something it cannot return, since there is no way to modify what it returns. So the test is kind of useless, if you know what I mean

If you had a setter, your tests would made more sense


        $object = new SomeClass();

        $obj = new stdClass();
        $obj->name = 'Bill';
        
        $object->setObject($obj);

        $this->assertEquals($obj, $object->getObject());

Dmitrev avatar Jul 20 '22 09:07 Dmitrev