I have been trying to write a simple Unit Test on PHP version 8.0.1 and PHPUnit 9, with the same logic I been doing this on the older version (PHP: 7.4, PHPUnit 7):
MysqlService.php
public function doSomething()
{
return null;
}
UserService.php
public function doSomething()
{
return $this->mysqlService->doSomething();
}
UserServiceTest.php
/**
* @test
*/
public function doSomething_test()
{
$mock['mysqlService'] = $this->getMockBuilder(MysqlService::class)
->setMethods(['doSomething'])
->disableOriginalConstructor()
->getMock();
$mock['mysqlService']->expects($this->once())
->method('doSomething')
->willReturn('mockedValue');
$userService = new UserService();
$this->assertEquals('mockedValue', $userService->doSomething());
}
In this example, I'm simply trying to mock the result of MysqlService->doSomething()
to be mockedValue
, but when I ran the command:
./vendor/bin/phpunit tests/Unit/Service/UserServiceTest.php
I get
root@30fdcf7735ea:/var/www/html# ./vendor/bin/phpunit tests/Unit/Service/UserServiceTest.php
PHPUnit 9.5.1 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 00:00.465, Memory: 6.00 MB
There was 1 failure:
1) UserServiceTest::doSomething_test
Failed asserting that null matches expected 'mockedValue'.
/var/www/html/tests/Unit/Service/UserServiceTest.php:247
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
I might be doing something wrong that changed in the new version but googling didn't help.
Any help would be appreciated.
question from:
https://stackoverflow.com/questions/65890311/php-unit-9-mock-fails 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…