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
}