2016-04-25 131 views
1

目前,我正在为使用组件的类编写集成测试。由于此组件使用第三方服务(在本例中为AWS S3),我想用模拟组件替换组件,以避免与第三方服务进行任何通信。控制器类的将模拟组件注入控制器 - 集成测试 - cakephp 3

部分:

class AlbumsController extends AppController{ 
     public $components = ['Aws', 'Upload']; 
     // Example of function that uses component 
     public function add(){ 
      $album->pictures = $this->Aws->transformLinkIntoPresignedUrl($album->pictures); 
     } 
} 

集成测试的部分:

public function controllerSpy($event){ 
    parent::controllerSpy($event); 
    if (isset($this->_controller)) { 
     $this->_controller->Auth->setUser([ 
      'id' => $this->userId, 
      'username' => 'testtesttesttest', 
      'email' => '[email protected]', 
      'first_name' => 'Mark', 
      'last_name' => 'van der Laan', 
      'uuid' => 'wepoewoweo-ew-ewewpoeopw', 
      'sign_in_count' => 1, 
      'current_sign_in_ip' => '127.0.0.1', 
      'active' => true 
     ]); 
     // If the component is set, inject a mock 
     if($this->_controller->Aws){ 
      $component = $this->getMock('App\Controller\Component\AwsComponent'); 
      $component->expects($this->once()) 
       ->method('transformLinkIntoPresignedUrl') 
       ->will($this->returnValue(['link'])); 
      $this->_controller->Aws = $component; 
     } 
    } 
} 

由于此抛出transformLinkIntoPresignedUrl不存在的错误,我不知道如果我在这个特定问题的正确轨道。因此,我的问题是,如何将模拟/存根组件注入控制器并控制其行为(通过设置方法的固定返回值)?

回答

0

当我在查看IntegrationTestCase的代码时,我发现无法做你(和我)正在尝试做的事情。我能想出的最好的是:

$this->controller = new AlbumsController(); 

$this->controller->Aws = $this->createMock(AwsComponent::class); 
$this->controller->Aws 
    ->expects($this->once()) 
    ->method('transformLinkIntoPresignedUrl'); 

$this->controller->add(); 

但这也意味着你必须做出的闪存,验证,请求和你认为理所当然,因为控制器在虚空只是做其他呼叫嘲笑。在这里,我达到了我的蛋糕知识的极限。