【问题标题】:cakephp test component failedcakephp 测试组件失败
【发布时间】:2014-09-02 19:19:33
【问题描述】:

我有一个用 cakephp 开发的网站,其中包含一个我想用 PHPUnit 测试的组件。

我创建了一个名为 CurrencyConverter 的插件,并在其中放入了一个组件:

Plugin/CurrencyConverter/Controller/Component/CurrencyConverterComponent.php

现在我想测试我的代码。

我已经创建了一个文件 CurrencyConverterTest.php 到:

Test/Case/Controller/Component/CurrencyConverterTest.php

这是测试文件:

<?php
class CurrencyConverterTestCase extends CakeTestCase {
    var $uses = null;
    public $CurrencyConverter;

    function testConverter() {
        $this->CurrencyConverter = ClassRegistry::init('CurrencyConverterComponent');
        $price = $this->CurrencyConverter->convert('EUR', 'EUR', '1000', 0, 0);
        echo($price);
    }
}
?>

如果我运行测试返回此错误:

MISSINGTABLEEXCEPTION
Table currency_converter_components for model CurrencyConverterComponent was not found in datasource test.
Test case: CurrencyConverterTestCase(testConverter)

在我的组件中现在没有对数据库的调用,我如何告诉测试不要使用模型?

或者我必须创建一个?

谁能解释我如何在不使用数据库的情况下测试组件?

谢谢

【问题讨论】:

    标签: php unit-testing cakephp phpunit


    【解决方案1】:

    错了:

    ClassRegistry::init('CurrencyConverterComponent');
    

    被认为是加载模型,它使用给定名称动态构建模型,并按照惯例查找该表currency_converter_components。

    我建议您查看 CakePHP 核心测试,例如 AuthComponent 测试作为如何在测试中实例化组件的示例。

    $request = new CakeRequest(null, false);
    $this->Controller = new AuthTestController($request, $this->getMock('CakeResponse'));
    $collection = new ComponentCollection();
    $collection->init($this->Controller);
    $this->Auth = new TestAuthComponent($collection);
    

    您的测试也缺少 setUp() 和 tearDown()。这看起来不像您阅读过有关测试的文档。 http://book.cakephp.org/2.0/en/development/testing.html#creating-your-first-test-case

    为什么 CurrencyConverter 还是一个组件?它处理数据,这显然应该是模型方法或行为。此外,您还缺少方法和属性前面的关键字。

    【讨论】:

    • 好的,我知道,但是您能否为我的组件提供一个简单的示例?因为 AuthComponent 测试不是那么容易理解,而且组件的范围完全不同
    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多