Cakephp 单元测试我将如何编写测试 buildRules 的测试方法

Cakephp unit test how I will write a test method for test buildRules

我正在尝试为以下代码编写测试用例

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['email']));

    return $rules;
}

我已经创建了 AdminUsersFixture 和 AdminUsersTableTest。 在 AdminUsersTableTest 中,我已经加载了 AdminUsersFixture。

我可以通过以下方法测试默认验证

public function testValidationDefault()
{
        $data = [
            'name' => 'lorem',
            'email' => 'jone@test.com',
            'password' => 'Lorem_ipsum',
            'status' => 1,
            'created' => date('Y-m-d H:i:s'),
            'modified' => date('Y-m-d H:i:s'),
        ];
        $adminUsers = $this->AdminUsers->newEntity($data);
        $this->assertEmpty($adminUsers->getErrors());
}

现在我将如何编写测试用例方法来测试 cakephp 构建规则?

验证规则适用于 patching/creating 一个实体,它们用于验证请求数据。保存实体时应用应用程序规则,它们用于验证 data/application 完整性。

所以你要保存一个实体(它必须没有任何验证错误,否则保存操作将在应用应用程序规则之前退出),然后检查可能的错误实体。

例如:

public function testApplicationRulesEmailsMustBeUnique()
{
    $adminUser = $this->AdminUsers->newEmptyEntity();
    $adminUser->email = 'already@existing.email';
    
    $this->assertFalse($this->AdminUsers->save($adminUser));
    
    $this->assertSame(
        ['_isUnique' => 'This value is already in use'],
        $adminUser->getError('email')
    );
}
public function testSavingSucceeds()
{
    $data = [
        'name' => 'lorem',
        'email' => 'jone@test.com',
        'password' => 'Lorem_ipsum',
        'status' => 1,
        'created' => date('Y-m-d H:i:s'),
        'modified' => date('Y-m-d H:i:s'),
    ];
    $adminUser = $this->AdminUsers->newEntity($data);
    
    $this->assertInstanceOf(
        \Cake\Datasource\EntityInterface::class, 
        $this->AdminUsers->save($adminUser)
    );
    $this->assertEmpty($adminUser->getErrors());
    
    // ...
}

您也可以使用 checkRules 方法,checkRules 将 return bool 用于创建、更新或删除。

public function testBuildRulesEmailUnique()
{   
        $this->assertFalse( 
            $this->AdminUsers->checkRules(
               $this->AdminUsers->newEntity([
                   'email' => 'jone@test.com'
               ])
        ));
}