cakephp3 test component在非对象上调用on()上的成员函数

时间:2015-04-08 06:53:53

标签: php cakephp testing tdd cakephp-3.0

我正在尝试测试为cakephp 3编写的插件组件。

这是我的组成部分:

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 test:

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

我该如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:2)

我这个特殊情况你是在嘲笑太多。你告诉phpunit在控制器中模拟所有方法,包括eventManager() getter方法,这会让控制器尝试在空对象上调用on()

您只需要模拟您感兴趣的测试方法,这将改变环境,或尝试与外部服务进行通信。此外,您似乎正在尝试测试Component而不是Controller,测试的目的不是很明确。

对我而言,您的CurrencyConverter类似乎不应该是一个组件,而只是您可以在任何地方使用的项目中的类。没有必要将这样的类附加到控制器上。