phpunit
phpunit copied to clipboard
Is not possible mock method called in constructor
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.
I do not understand what you are trying to report.
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
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());