Cakephp 3 - 单元测试验证默认

时间:2016-02-24 23:27:30

标签: 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&amp; 0000000011b3c53b0000000040aca14b为真'。有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

查看Table::save()返回的内容,\Cake\Datasource\EntityInterface|bool。成功时,它返回持久化实体,失败时返回布尔值false。所以你的保存操作成功,它将返回一个实体,因此错误。

如果要测试验证,则应使用表类提供的验证程序对象(Table::validationDefault()通过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
}

另见