php - Cakephp 测试数据库 - 模型问题

标签 php database unit-testing cakephp testing

我在项目中进行 phpunit 测试时遇到问题。 Organization 模型无法在 $test 数据库上运行,而其余模型可以运行。我什至不知道组织的固定装置是否被添加到测试数据库中,因为它总是查询 default 数据库。

代码如下:

我正在测试的方法:

public function guardarInformacion($usuario=null, $organizacion=null){
    if($usuario==null || $organizacion==null):
        throw new CakeException('Datos insuficientes');
    endif;

    $this->User->create();
    $this->Organization->create();
    Debugger::dump($this->Organization->find('all'));
    if($this->User->save(array('User'=>$usuario))):
        if(!$this->Organization->save(array('Organization'=>$organizacion))):
            Debugger::dump($this->Organization->invalidFields());
            $this->User->delete('last');
            throw new CakeException('Ocurrio un problema al ingresar los datos');
        endif;
    endif;
}

测试类:

<?php
App::uses('OrganizationsController', 'Controller');
App::import('Controller', 'Organizations');
App::import('Model', 'Organization');

/**
 * OrganizationsController Test Case
 *
 */
class OrganizationsControllerTest extends ControllerTestCase {

/**
* Variable que contiene un controlador de organizacion
*/
    public $OrganizationsController = null;

/**
* Variable que contiene un modelo de organizacion
*/
    public $Organization = null;

/**
 * Fixtures
 *
 * @var array
 */
    public $fixtures = array(
        'app.organization',
        'app.city',
        'app.departament',
        'app.country',
        'app.user'
    );

    /**
    * Método que se ejecuta cada vez antes de que se ejecute
    * un test
    *
    * @return void
    */
        public function setUp(){
            parent::setUp();
            $this->OrganizationsController = new OrganizationsController();
            $this->Organization = new Organization();
        }

    /**
    * Test del método guardarInformacion
    *
    * @return void
    */
    public function testGuardarInformacion(){
        $user= array(
            'id' => 10,
            'password' => 'passwordTest',
            'username' => 'usernameTest'
        );

        $organization = array(
            'user_id' => 10,
            'nit' => 'nitX',
            'nombre' => 'nombreX',
            'sigla' => 'siglaX',
            'telefono' => 1,
            'fax' => 'faxX',
            'email' => 'emailX@email.com',
            'sitio_web' => 'sitio_webX',
            'city_id' => 1,
            'rep_nombres' => 'rep_nombresX',
            'rep_primer_apellido' => 'rep_primer_apellidoX',
            'rep_segundo_apellido' => 'rep_segundo_apellidoX',
            'rep_tipo_documento' => 1,
            'rep_direccion' => 'rep_direccionX',
            'rep_telefono' => 'rep_telefonoX',
            'rep_email' => 'rep_emailX',
            'adm_nombres' => 'adm_nombresX',
            'adm_primer_apellido' =>
            'adm_primer_apellidoX',
            'adm_segundo_apellido' => 'adm_segundo_apellidoX',
            'adm_cargo' => 'adm_cargo1',
            'adm_tipo_documento' => 1,
            'adm_numero_documento' => 'adm_numero_documentoX',
            'adm_telefono' => 'adm_telefonoX',
            'adm_email' => 'adm_emailX',
            'certificacion_codigo' =>
            'certificacion_codigoX',
            'certificacion_fecha' => '2014-11-03'
        );

        $this->OrganizationsController->guardarInformacion($user, $organization);
        $aux = $this->Organization->findByUser_id('10');
        Debugger::dump($aux);
        $this->assertEquals('nombreX', $aux['Organization']['nombre']);
    }

    /**
        * Método que se ejecuta desdepués de cada test
        *
        * @return void
        */
        public function tearDown(){
            parent::tearDown();
            $this->OrganizationsController = null;
            $this->Organization = null;
        }
}

夹具:

<?php
/**
 * OrganizationFixture
 *
 */
class OrganizationFixture extends CakeTestFixture {

/**
 * Fields
 *
 * @var array
 */
    public $fields = array(
        'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false, 'key' => 'primary'),
        'user_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false, 'key' => 'unique', 'comment' => 'Heredada, corresponde a los datos que hacen de organización un usuario del sistema.'),
        'nit' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 11, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'nombre' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 60, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'sigla' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 10, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'telefono' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false),
        'fax' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'email' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'sitio_web' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'city_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false, 'key' => 'index'),
        'rep_nombres' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'rep_primer_apellido' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'rep_segundo_apellido' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'rep_tipo_documento' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false),
        'rep_direccion' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'rep_telefono' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'rep_email' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_nombres' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_primer_apellido' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_segundo_apellido' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_cargo' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_tipo_documento' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false),
        'adm_numero_documento' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_telefono' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'adm_email' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'certificacion_codigo' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 45, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
        'certificacion_fecha' => array('type' => 'date', 'null' => true, 'default' => null),
        'indexes' => array(
            'PRIMARY' => array('column' => 'id', 'unique' => 1),
            'user_id_UNIQUE' => array('column' => 'user_id', 'unique' => 1),
            'fk_organizations_users1_idx' => array('column' => 'user_id', 'unique' => 0),
            'fk_organizations_cities1_idx' => array('column' => 'city_id', 'unique' => 0)
        ),
        'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
    );

/**
 * Records
 *
 * @var array
 */
    public $records = array(
        array(
            'id' => 1,
            'user_id' => 1,
            'nit' => 'Lorem ips',
            'nombre' => 'Lorem ipsum dolor sit amet',
            'sigla' => 'Lorem ip',
            'telefono' => 1,
            'fax' => 'Lorem ipsum dolor sit amet',
            'email' => 'email@corre.com',
            'sitio_web' => 'Lorem ipsum dolor sit amet',
            'city_id' => 1,
            'rep_nombres' => 'Lorem ipsum dolor sit amet',
            'rep_primer_apellido' => 'Lorem ipsum dolor sit amet',
            'rep_segundo_apellido' => 'Lorem ipsum dolor sit amet',
            'rep_tipo_documento' => 1,
            'rep_direccion' => 'Lorem ipsum dolor sit amet',
            'rep_telefono' => 'Lorem ipsum dolor sit amet',
            'rep_email' => 'Lorem ipsum dolor sit amet',
            'adm_nombres' => 'Lorem ipsum dolor sit amet',
            'adm_primer_apellido' => 'Lorem ipsum dolor sit amet',
            'adm_segundo_apellido' => 'Lorem ipsum dolor sit amet',
            'adm_cargo' => 'Lorem ipsum dolor sit amet',
            'adm_tipo_documento' => 1,
            'adm_numero_documento' => 'Lorem ipsum dolor sit amet',
            'adm_telefono' => 'Lorem ipsum dolor sit amet',
            'adm_email' => 'Lorem ipsum dolor sit amet',
            'certificacion_codigo' => 'Lorem ipsum dolor sit amet',
            'certificacion_fecha' => '2014-11-04'
        ),
    );

}

数据库:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => 'root',
    'database' => 'colciencias'
);

public $test = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => 'root',
    'database' => 'colcienciastest'
);

错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`colciencias`.`organizations`, CONSTRAINT `fk_organizations_users1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

如您所见,它使用的是 colciencias.`organizations,而不是 'colcienciastest'.'organizations'。

最佳答案

我解决了这个问题,即使没有出现异常或警告,我也有这 2 条导入行:

App::import('Controller', 'Organizations');
App::import('Model', 'Organization');

哪里错了,它没有破坏代码,也没有出现异常。只需删除它们就可以正确地部署测试。

更新: 我不太确定,我今天创建了另一个测试用例,当我创建一个模型时遇到了同样的问题,解决方案是从 Controller 调用模型而不只是创建一个实例: $this->Controller->Model->function()

我没有发现任何有关,也不知道在测试用例或任何地方导入和创建模型是否错误。

更新:解决方案: 问题始终在于 Cakephp 中的模型无法以 new Model(); 方式创建。在 cakephp 中,您必须按以下方式使用 ClassRegistry 创建一个新类:

$model = ClassRegistry::init('ModelName');

不使用这种调用方式,甚至可以让您的软件正常工作,但绝对不使用它会带来问题,就像我遇到的那样。

关于php - Cakephp 测试数据库 - 模型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26738369/

相关文章:

php - 正确使用ini_set()的方法

php - 如何告诉 phpunit 在失败时停止

php - 显示带有分组条的垂直条形图。

mysql - 外键循环引用困境

c# - 单元测试,模拟 - 简单案例 : Service - Repository

php - 使用 PHP 从 XML 中删除空标签

json - 如何使用aerospike查询语言导入json数据?

mysql - 有没有更简单的方法来实现这种用户消息传递方式?

Java 泛型 : <? > vs 捕获<?>

python - 使用 pytest 模拟 psycopg2 的正确方法是什么?