PHPUnit - 模拟 S3Client 运行不正常

标签 php amazon-s3 mocking tdd phpunit

库:“aws/aws-sdk-php”:“2.*”
PHP版本:PHP 5.4.24 (cli)

Composer .json

{
    "require": {
        "php": ">=5.3.1",
        "aws/aws-sdk-php": "2.*",
        ...
    },

    "require-dev": {
        "phpunit/phpunit": "4.1",
        "davedevelopment/phpmig": "*",
        "anahkiasen/rocketeer": "*"
    },
    ...
}

我们制作了一个 AwsWrapper 来获取功能操作:uploadFile、deleteFile...
您可以阅读该类,使用依赖注入(inject)进行单元测试。
关注构造函数和内部 $this->s3Client->putObject(...) 对 uploadFile 函数的调用。

<?php

namespace app\lib\modules\files;

use Aws\Common\Aws;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use core\lib\exceptions\WSException;
use core\lib\Injector;
use core\lib\utils\System;

class AwsWrapper
{

  /**
   * @var \core\lib\Injector
   */
  private $injector;

  /**
   * @var S3Client
   */
  private $s3Client;

  /**
   * @var string
   */
  private $bucket;

  function __construct(Injector $injector = null, S3Client $s3 = null)
  {
    if( $s3 == null )
    {
      $aws = Aws::factory(dirname(__FILE__) . '/../../../../config/aws-config.php');
      $s3 = $aws->get('s3');
    }
    if($injector == null)
    {
      $injector = new Injector();
    }
    $this->s3Client = $s3;
    $this->bucket = \core\providers\Aws::getInstance()->getBucket();
    $this->injector = $injector;
  }

  /**
   * @param $key
   * @param $filePath
   *
   * @return \Guzzle\Service\Resource\Model
   * @throws \core\lib\exceptions\WSException
   */
  public function uploadFile($key, $filePath)
  {
    /** @var System $system */
    $system = $this->injector->get('core\lib\utils\System');
    $body   = $system->fOpen($filePath, 'r');
    try {
      $result = $this->s3Client->putObject(array(
        'Bucket' => $this->bucket,
        'Key'    => $key,
        'Body'   => $body,
        'ACL'    => 'public-read',
      ));
    }
    catch (S3Exception $e)
    {
      throw new WSException($e->getMessage(), 201, $e);
    }

    return $result;
  }

} 

测试文件将我们的 Injector 和 S3Client 实例作为 PhpUnit MockObject。要模拟 S3Client,我们必须使用 Mock Builder 禁用原始构造函数。

模拟 S3Client:

$this->s3Client = $this->getMockBuilder('Aws\S3\S3Client')->disableOriginalConstructor()->getMock();

要配置内部 putObject 调用(用 putObject 抛出 S3Exception 进行测试的情况,但我们对 $this->returnValue($expected) 有同样的问题。

初始化测试类并配置sut:

  public function setUp()
  {
    $this->s3Client = $this->getMockBuilder('Aws\S3\S3Client')->disableOriginalConstructor()->getMock();
    $this->injector = $this->getMock('core\lib\Injector');
  }

  public function configureSut()
  {
    return new AwsWrapper($this->injector, $this->s3Client);
  }

无效代码:

$expectedArray = array(
  'Bucket' => Aws::getInstance()->getBucket(),
  'Key'    => $key,
  'Body'   => $body,
  'ACL'    => 'public-read',
);
$this->s3Client->expects($timesPutObject)
  ->method('putObject')
  ->with($expectedArray)
  ->will($this->throwException(new S3Exception($exceptionMessage, $exceptionCode)));
$this->configureSut()->uploadFile($key, $filePath);

当我们执行我们的测试函数时,注入(inject)的S3Client没有抛出异常也没有返回预期的值,总是返回NULL。

通过 xdebug,我们已经看到 S3Client MockObject 配置正确,但不能像 will() 配置的那样工作。

一个“解决方案”(或一个糟糕的解决方案)可能是做一个 S3ClientWrapper,这只会将问题转移到其他不能用 mock 进行单元测试的类。

有什么想法吗?

更新 使用 xdebug 配置 MockObject 的屏幕截图: enter image description here

最佳答案

以下代码按预期运行和通过,因此我认为您不会遇到由 PHPUnit 或 AWS SDK 引起的任何限制。

<?php

namespace Aws\Tests;

use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Guzzle\Service\Resource\Model;

class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testMockCanReturnResult()
    {
        $model = new Model([
            'Contents' => [
                ['Key' => 'Obj1'],
                ['Key' => 'Obj2'],
                ['Key' => 'Obj3'],
            ],
        ]);

        $client = $this->getMockBuilder('Aws\S3\S3Client')
            ->disableOriginalConstructor()
            ->setMethods(['listObjects'])
            ->getMock();
        $client->expects($this->once())
            ->method('listObjects')
            ->with(['Bucket' => 'foobar'])
            ->will($this->returnValue($model));

        /** @var S3Client $client */
        $result = $client->listObjects(['Bucket' => 'foobar']);

        $this->assertEquals(
            ['Obj1', 'Obj2', 'Obj3'],
            $result->getPath('Contents/*/Key')
        );
    }

    public function testMockCanThrowException()
    {
        $client = $this->getMockBuilder('Aws\S3\S3Client')
            ->disableOriginalConstructor()
            ->setMethods(['getObject'])
            ->getMock();
        $client->expects($this->once())
            ->method('getObject')
            ->with(['Bucket' => 'foobar'])
            ->will($this->throwException(new S3Exception('VALIDATION ERROR')));

        /** @var S3Client $client */
        $this->setExpectedException('Aws\S3\Exception\S3Exception');
        $client->getObject(['Bucket' => 'foobar']);
    }
}

您还可以使用 Guzzle MockPlugin如果您只想模拟响应而不关心模拟/ stub 对象。

关于PHPUnit - 模拟 S3Client 运行不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24080306/

相关文章:

php - 通过 laravel 框架集成现有项目?

html - AWS S3 相同图像,不同尺寸

c# - 模拟和单例

python - 在 Python 中模拟远程主机

php - 如何使用php在linux上获取c++编译结果

javascript - 如何在一个页面中处理多个表单

amazon-web-services - 使用亚马逊数据管道将dynamoDB数据备份到S3

amazon-web-services - 如何将数据从 S3 存储桶传输到 Kafka

python - 模拟函数内部导入的模块

php - 什么是 PHP 中的参数签名?