首页 > 解决方案 > PHP 单元 9 模拟失败

问题描述

我一直在尝试在 PHP 8.0.1 和 PHPUnit 9 上编写一个简单的单元测试,其逻辑与我在旧版本(PHP:7.4,PHPUnit 7)上所做的相同:

mysql服务.php

 public function doSomething()
    {
        return null;
    }

用户服务.php

public function doSomething()
    {
        return $this->mysqlService->doSomething();
    }

用户服务测试.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());
    }

在这个例子中,我只是试图模拟MysqlService->doSomething()to be的结果mockedValue,但是当我运行命令时:

./vendor/bin/phpunit tests/Unit/Service/UserServiceTest.php

我明白了

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.

我可能做错了什么,在新版本中发生了变化,但谷歌搜索没有帮助。任何帮助,将不胜感激。

标签: phpunit-testingmocking

解决方案


推荐阅读