Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHPUnit模拟函数调用_Php_Unit Testing_Mocking_Phpunit - Fatal编程技术网

PHPUnit模拟函数调用

PHPUnit模拟函数调用,php,unit-testing,mocking,phpunit,Php,Unit Testing,Mocking,Phpunit,我希望测试的对象中有以下函数 public function getUser($credentials, UserProviderInterface $userProvider) { $resourceOwner = $this->getAuthClient()->fetchUserFromToken($credentials); // ... Code to create user if non-existent, update values, etc.

我希望测试的对象中有以下函数

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $resourceOwner = $this->getAuthClient()->fetchUserFromToken($credentials);

    // ... Code to create user if non-existent, update values, etc.
    // ... Basically the code I want to test is here

    return $user;
}

getAuthClient()
调用返回一个
Client
对象,其可用函数为
fetchUserFromToken


在PHPUnit测试中,如何模拟
fetchUserFromToken
以仅返回
ResourceOwner
对象?因为实际的函数执行很多身份验证机制,并且不在本测试用例的范围之内,所以我找到了一个名为的php库,但这不是我想要仔细研究的方法。对于手头的问题来说,这让人觉得既讨厌又过分

getAuthClient()
函数定义如下

private function getAuthClient() {
   return $this->clients->getClient('auth');
}
构造函数定义了
$this->clients

public function __construct(ClientRepo $clients) {
    $this->clients = $clients;
}
因此,我模拟了
ClientRepo
,并公开了
getClient()
方法来返回
AuthClient
的模拟(无论输入如何),以便控制
fetchUserFromToken()
调用的返回

public function testGetUser() {
    $client = $this->createMock(WebdevClient::class);
    $client->expects($this->any())
        ->method('fetchUserFromToken')
        ->will($this->returnCallback(function()
        {
            // TARGET CODE
        }));

    $clients = $this->createMock(ClientRegistry::class);
    $clients->expects($this->any())
        ->method('getClient')
        ->will($this->returnCallback(function() use ($client)
        {
            return $client;
        }));

    $object = new TargetObject($clients);

    $result = $object->getUser(...);

    // ... Assertions to follow
}