【问题标题】:PHPUnit Mock Function CallPHPUnit 模拟函数调用
【发布时间】:2020-05-08 23:50:29
【问题描述】:

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

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 unit-testing mocking phpunit


    【解决方案1】:

    我找到了一个名为 Runkit 的 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
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-18
      • 2017-01-13
      • 1970-01-01
      • 2016-01-30
      • 2015-10-03
      • 2013-02-23
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多