模拟类时的嘲弄类型错误
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');
【讨论】:
以上是关于模拟类时的嘲弄类型错误的主要内容,如果未能解决你的问题,请参考以下文章