2015-04-08 30 views
0

我想測試我的CakePHP插件組件寫上3cakephp3測試組件來調用一個成員函數()一個非對象

這是我的組件:

namespace CurrencyConverter\Controller\Component; 

use Cake\Controller\Component; 
use Cake\Datasource\ConnectionManager; 
use Cake\ORM\TableRegistry; 

class CurrencyConverterComponent extends Component 
{ 
    public $controller = null; 

    public function setController($controller) 
    { 
     $this->controller = $controller; 
    } 

    public function startup($event) 
    { 
     $this->setController($event->subject()); 
    } 


    public function convert($fromCurrency, $toCurrency, $amount, $saveIntoDb = 1, $hourDifference = 1, $dataSource = 'default') { 

    } 
} 

和這是mt測試:

namespace App\Test\TestCase\Controller\Component; 

use CurrencyConverter\Controller\Component\CurrencyConverterComponent; 
use Cake\Controller\Controller; 
use Cake\Controller\ComponentRegistry; 
use Cake\Network\Request; 
use Cake\Network\Response; 
use Cake\TestSuite\TestCase; 

class CurrencyConverterComponentTest extends TestCase { 
    public $fixtures = ['app.currencyconverter']; 
    public $CurrencyConverter = null; 
    public $controller = null; 

    public function setUp() { 
     parent::setUp(); 
     // Setup our component and fake test controller 
     $request = new Request(); 
     $response = new Response(); 
     $this->controller = $this->getMock(
      'Cake\Controller\Controller', 
      [], 
      [$request, $response] 
     ); 
     $registry = new ComponentRegistry($this->controller); 
     $this->CurrencyConverter = new CurrencyConverterComponent($registry); 
    } 

    public function testAmountWithComma() { 
     $fromCurrency = 'EUR'; 
     $toCurrency  = 'GBP'; 
     $amount   = '20,00'; 
     $saveIntoDb  = 0; 
     $hourDifference = 0; 
     $dataSource  = 'test'; 

     $result = $this->CurrencyConverter->convert($fromCurrency, $toCurrency, $amount, $saveIntoDb, $hourDifference, $dataSource); 

     $this->assertGreaterThan($result, $amount); 
    } 
} 

當我運行測試時,我得到這個錯誤的核心!

Fatal error: Call to a member function on() on a non-object in /Users/alessandrominoccheri/Sites/cakephp3/vendor/cakephp/cakephp/src/Controller/Controller.php on line 289 

我該如何解決這個問題?

謝謝

+0

你想在這裏測試什麼?組件或控制器? –

+0

這個測試中的組件@JoséLorenzo –

回答

2

我這種特殊的情況,你嘲笑太多。您正在告訴phpunit在控制器中模擬全部方法,其中包括eventManager() getter方法,這使得控制器嘗試在空對象上調用on()

您只需要模擬您對測試感興趣的方法,這會改變環境,或嘗試與外部服務進行通信。此外,似乎您正在嘗試測試組件而不是Controller,測試的目的不是很清楚。

對我來說,你的CurrencyConverter類看起來不應該是一個組件,而只是你的項目中一個可以在任何地方使用的類。沒有必要爲控制器添加這樣的類。

+0

好的,但在這種情況下,我需要將它用作組件,因爲我省略了其餘的代碼。請你讓我知道如何解決模擬問題?謝謝 –

+0

'$ component = new CurrencyConverter(new ComponentRegistry(new Controller))' –

+0

yes now it works fine!謝謝 –

相關問題