模拟类时的嘲弄类型错误

Posted

技术标签:

【中文标题】模拟类时的嘲弄类型错误【英文标题】:Mockery TypeError when mocking class 【发布时间】:2020-09-14 16:34:02 【问题描述】:

我正在尝试创建一个模拟对象并将其传递给构造函数。我收到了错误

Users            
 ✘ GetUser ItShouldThrowAnExceptionIfUserDoesNotExist
   ┐
   ├ Failed asserting that exception of type "TypeError" matches expected exception "Foo\Exceptions\UserNotFoundException". Message was: "Argument 2 passed to Foo\Clients\Users::__construct() must be an instance of Foo\Api\UsersApi, instance of Mockery_0__UsersApi given, called in /Users/tomcaflisch/myproject/tests/Clients/UsersTest.php on line 25" at
   ├ /Users/tomcaflisch/myproject/lib/Clients/Users.php:26                                                                                                                                                                                                                                                                                                                                     
   ├ /Users/tomcaflisch/myproject/tests/Clients/UsersTest.php:25                                                                                                                                                                                                                                                                                                                               
   ├ .                                                                                                                                                                                                                                                                                                                                                                                                                 
   ┴

根据the docs,这应该可以工作。

用户类

class Users

    public function __construct(?string $secret, UsersApi $usersApi = null)
    
    

UsersTest 类

use Mockery\Adapter\Phpunit\MockeryTestCase;

class UsersTest extends MockeryTestCase

    public function testGetUser_ItShouldThrowAnExceptionIfUserDoesNotExist()
    
        $this->expectException(UserNotFoundException::class);
        $this->expectExceptionMessage("User with id, email, or username foo@bar.com not found");

        $usersApi = Mockery::mock('UsersApi');
        $usersApi->shouldReceive('get')
            ->andThrow(new UserNotFoundException("User with id, email, or username foo@bar.com not found"));

        $usersClient = new Users(null, $usersApi);
    

【问题讨论】:

【参考方案1】:

啊,我刚刚想通了。我需要使用完整的命名空间。

替换

$usersApi = Mockery::mock('UsersApi');

$usersApi = Mockery::mock('Foo\Api\UsersApi');

【讨论】:

以上是关于模拟类时的嘲弄类型错误的主要内容,如果未能解决你的问题,请参考以下文章

嘲弄:被动部分模拟与默认模拟有何不同?

错误:在 null 上调用成员函数 create(),单元测试(嘲弄)

嘲弄和method_exists

嘲弄模拟不返回指定值

Laravel 的嘲弄不会模拟方法

laravel 4 嘲弄模拟模型关系