Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

PHP Unit 9 mock fails

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...