2016-04-25 126 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(); 

但這也意味着你必須做出的閃存,驗證,請求和你認爲理所當然,因爲控制器在虛空只是做其他呼叫嘲笑。在這裏,我達到了我的蛋糕知識的極限。