PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

[FIXED] Cakephp unit test how I will write a test method for test buildRules

 December 30, 2021     cakephp, cakephp-4.x     No comments   

Issue

I am trying to write a test case for below codes

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

    return $rules;
}

I already created AdminUsersFixture and AdminUsersTableTest. In AdminUsersTableTest I already load AdminUsersFixture.

I am able to test default validation by below method

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());
}

Now how I will write a test case method to test cakephp buildRules ?


Solution

Validation rules are applied when patching/creating an entity, they are ment to validate request data. Application rules are being applied when saving entities, they are ment to validate data/application integrity.

So you would save an entity (it must not have any validation errors, otherwise the saving operation will bail out before applying application rules), and then check for possible errors on the entity.

For example:

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());
    
    // ...
}


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing