如何存根返回数组的方法

时间:2018-01-15 05:04:55

标签: php unit-testing mocking phpunit tdd

我有这样的DocumentService类:

namespace App\Services;

use App\Api\StorageServiceInterface;

class DocumentService
{

    private $storageService;

    function __construct(StorageServiceInterface $storageService)
    {
        $this->storageService = $storageService;
    }

    public function createFolder(User $user)
    {
        $folderData = $this->storageService->createFolder(
            '/Users/' . $user->email
        );

        $user->folder = $folderData['folder_id'];
        $user->save();

        return $user->folder;
    }
}

LocalStorageService的部分实施。

namespace App\Api;

class LocalStorageService implements StorageServiceInterface
{
    public function createFolder($folder)
    {
        ...

        return ['folder_id' => $folder_id, 'folder_path' => $folder_path];
    }
}

我正在测试DocumentService课程。我试图模仿实现createFolder()的{​​{1}}上的LocalStorageService方法。

如何配置此存根以使用PHPUnit返回数组?

我试过这个:(我测试的部分代码)

StorageServiceInterface

但我只是 random_id

1 个答案:

答案 0 :(得分:0)

虽然它应该适用于类和接口,但接口应该是首选,因为这是接口的客户端所期望的。

以下内容应该有效:

public function testCreateFolder()
{
    $user = factory(User::class)->make();
    $folderPath = '/Users/' . $user->email;

    $localStorageService = $this->createMock(StorageServiceInterface::class);

    $localStorageService
        ->expects($this->once())
        ->method('createFolder')
        ->with($folderPath)
        ->willReturn(
            ['folder_id' => 'random_id', 'folder_path' => $folderPath]
        );


     $documentService = new DocumentService($localStorageService);
     $documentService->createFolder($user);
}

通过添加with()调用,只有在传递路径时才会确定它返回给定的数组。