unit-testing - Cakephp 3 - 单元测试验证默认

标签 unit-testing cakephp cakephp-3.x

我目前正在尝试为以下模型编写单元测试:

<?php
namespace App\Model\Table;

use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Users Model
 *
 * @property \Cake\ORM\Association\HasMany $Comments
 * @property \Cake\ORM\Association\BelongsToMany $Albums
 */
 class UsersTable extends Table
 {

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
     public function initialize(array $config)
     {
       parent::initialize($config);

       $this->table('users');
       $this->displayField('id');
       $this->primaryKey('id');

       $this->addBehavior('Timestamp');

       $this->hasMany('Comments', [
           'foreignKey' => 'user_id'
       ]);
       $this->belongsToMany('Albums', [
          'foreignKey' => 'user_id',
          'targetForeignKey' => 'album_id',
          'joinTable' => 'users_albums'
       ]);
      }

/**
 * @Author: Mark van der Laan
 * @Date: 23-02-2016
 * @Description: Validating rules for the user model. Some additional, more complex validation rules are added.
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    // id
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    // username
    $validator
        ->requirePresence('username', 'create')
        ->notEmpty('username')
        // Enabled, just in case that the username will be an email address
        ->email('username')
        ->add('username', [
            'length' => [
                'rule' => ['minLength', 7],
                'message' => 'Username needs to be at least 7 characters long!',
            ]
        ]);

    // password
    $validator
        ->requirePresence('password', 'create')
        ->notEmpty('password')
        ->add('password', [
            'length' => [
                'rule' => ['minLength', 7],
                'message' => 'Password needs to be at least 7 characters long!',
            ]
        ]);

    // sign_in_count
    $validator
        ->integer('sign_in_count')
        ->requirePresence('sign_in_count', 'create')
        ->notEmpty('sign_in_count');

    // ip address
    $validator
        ->allowEmpty('current_sign_in_ip')
        ->requirePresence('current_sign_in_ip', 'create')
        // Currently checking for both IPv4 and IPv6 addresses
        ->ip('current_sign_in_ip', 'both');

    // active
    $validator
        ->boolean('active')
        ->requirePresence('active', 'create')
        ->allowEmpty('active');

    return $validator;
}

/**
 * Returns a rules checker object that will be used for validating
 * application integrity.
 *
 * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
 * @return \Cake\ORM\RulesChecker
 */
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['username']));
    return $rules;
}
}

测试validationDefault方法对我来说很重要,我尝试使用以下代码片段:

public function testValidationDefault()
{
    $data = ['username' => 'adminadmin@mixtureweb.nl',
             'password' => 'testtest123',
             'sign_in_count' => 0,
             'current_sign_in_ip' => '127.0.0.1',
             'active' => 'true'
            ];
    $this->assertTrue($this->Users->save($data));
    // $this->assertTrue($data);
}

当我尝试这样做时,这会抛出一个错误,指出我不应该将数组传递给 assertTrue 方法。因此,我试图找到示例,但我找不到任何东西。有没有人可以在其中找到如何对验证规则进行单元测试的引用资料? (到目前为止我在文档中找不到任何东西)

更新

public function testValidationDefault()
{
    $data = ['username' => 'adminadmin@mixtureweb.nl',
             'password' => 'testtest123',
             'sign_in_count' => 0,
             'current_sign_in_ip' => '127.0.0.1',
             'active' => true
            ];
    $user = $this->Users->newEntity($data);
    $saved = $this->Users->save($user);
    $this->assertTrue($saved);
    // $this->assertTrue($data);
}

这将给出“断言 App\Model\Entity\User Object &0000000011b3c53b0000000040aca14b 为真失败”。有谁知道我做错了什么?

最佳答案

看看 Table::save() 返回什么,它是 \Cake\Datasource\EntityInterface|bool。成功时返回持久实体,失败时返回 bool 值false。所以你的保存操作成功了,它会返回一个实体,因此会出现错误。

如果你想测试验证,你应该使用你的表类提供的验证器对象(Table::validationDefault() via Table::validator() ),或使用 Table::patchEntity()Table::newEntity() 并测试 Entity:errors() 的值。

修补/创建实体是在模型层进行验证的地方,保存过程只会应用应用程序规则。

public function testValidationDefault()
{
    $data = [
        'username' => 'adminadmin@mixtureweb.nl',
        'password' => 'testtest123',
        'sign_in_count' => 0,
        'current_sign_in_ip' => '127.0.0.1',
        'active' => true
    ];
    $user = $this->Users->newEntity($data);
    $this->assertEmpty($user->errors()); // empty = no validation errors
}

另见

关于unit-testing - Cakephp 3 - 单元测试验证默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35615316/

相关文章:

c# - 带有响应 header 的单元测试 webapi Controller

c# - 测试/验证弱引用

php - Cakephp 如何仅按日期和月份订购

php - 由一个相关表填充多个下拉菜单 CakePHP 3

php - CakePHP PDO 准备语句

unit-testing - rspec 单元测试具有无限循环的方法

unit-testing - 我应该如何处理 SimpleDB 中的最终一致性,特别是与单元测试相关的一致性?

mysql - CakePHP 3.x DB 映射,BelongsToMany 与 HasMany+HasOne

php - 带有子目录的 CakePHP 3 debug_kit

php - 在保存时更新实体而不是在插入时更新实体