【问题标题】: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);
    }

【问题讨论】:

    标签: php phpunit mockery


    【解决方案1】:

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

    替换

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

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

    【讨论】:

      猜你喜欢
      • 2014-01-29
      • 2017-12-27
      • 2018-10-31
      • 1970-01-01
      • 2014-01-16
      • 2019-06-26
      • 2018-04-05
      • 2015-07-17
      • 2019-02-09
      相关资源
      最近更新 更多