cakephp3测试组件在非对象上调用成员函数on()

cakephp3 test component Call to a member function on() on a non-object

我正在尝试测试为 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 测试:

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

我该如何解决这个问题?

谢谢

我这个特殊情况你嘲笑太多了。您告诉 phpunit 在控制器中模拟 all 方法,包括 eventManager() getter 方法,这使得控制器尝试调用 on()空对象。

您只需要模拟您有兴趣测试的方法,这将改变环境,或尝试与外部服务通信。另外,你好像是在测试Component而不是Controller,测试的目的不是很明确。

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