PHPUnit 模拟函数调用

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


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对象?因为实际函数做了很多认证机制,超出了本测试用例的范围


繁花如伊
浏览 97回答 1
1回答

梦里花落0921

我找到了一个名为Runkit的 php 库,但这不是我想要细读的方法。对于手头的问题,感觉很老套和矫枉过正。函数getAuthClient()定义如下private function getAuthClient() {   return $this->clients->getClient('auth');}由$this->clients构造函数定义public function __construct(ClientRepo $clients) {    $this->clients = $clients;}因此,我模拟ClientRepo并公开了getClient()返回 Mock 的方法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}
打开App,查看更多内容
随时随地看视频慕课网APP