2016-08-21 03:52:14 +05:30
|
|
|
<?php
|
2019-12-21 04:56:06 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2019-02-21 01:28:52 +05:30
|
|
|
namespace common\tests\unit\behaviors;
|
2016-08-21 03:52:14 +05:30
|
|
|
|
|
|
|
use common\behaviors\PrimaryKeyValueBehavior;
|
2019-02-21 01:28:52 +05:30
|
|
|
use common\tests\unit\TestCase;
|
2016-08-21 03:52:14 +05:30
|
|
|
use yii\db\ActiveRecord;
|
|
|
|
|
|
|
|
class PrimaryKeyValueBehaviorTest extends TestCase {
|
|
|
|
|
2019-12-21 04:56:06 +05:30
|
|
|
public function testGenerateValueForThePrimaryKey() {
|
|
|
|
$model = $this->createDummyModel();
|
|
|
|
$behavior = $this->createPartialMock(PrimaryKeyValueBehavior::class, ['isValueExists']);
|
|
|
|
$behavior->method('isValueExists')->willReturn(false);
|
|
|
|
$behavior->value = function() {
|
|
|
|
return 'mock';
|
|
|
|
};
|
|
|
|
|
|
|
|
$model->attachBehavior('primary-key-value-behavior', $behavior);
|
|
|
|
$behavior->setPrimaryKeyValue();
|
|
|
|
$this->assertSame('mock', $model->id);
|
2016-08-21 03:52:14 +05:30
|
|
|
}
|
|
|
|
|
2019-12-21 04:56:06 +05:30
|
|
|
public function testShouldRegenerateValueWhenGeneratedAlreadyExists() {
|
|
|
|
$model = $this->createDummyModel();
|
|
|
|
$behavior = $this->createPartialMock(PrimaryKeyValueBehavior::class, ['isValueExists', 'generateValue']);
|
|
|
|
$behavior->expects($this->exactly(3))->method('generateValue')->willReturnOnConsecutiveCalls('1', '2', '3');
|
|
|
|
$behavior->expects($this->exactly(3))->method('isValueExists')->willReturnOnConsecutiveCalls(true, true, false);
|
2016-08-21 03:52:14 +05:30
|
|
|
|
2019-12-21 04:56:06 +05:30
|
|
|
$model->attachBehavior('primary-key-value-behavior', $behavior);
|
|
|
|
$behavior->setPrimaryKeyValue();
|
|
|
|
$this->assertSame('3', $model->id);
|
|
|
|
}
|
2016-08-21 03:52:14 +05:30
|
|
|
|
2019-12-21 04:56:06 +05:30
|
|
|
private function createDummyModel() {
|
|
|
|
return new class extends ActiveRecord {
|
|
|
|
public $id;
|
2016-08-21 03:52:14 +05:30
|
|
|
|
2019-12-21 04:56:06 +05:30
|
|
|
public static function primaryKey() {
|
|
|
|
return ['id'];
|
|
|
|
}
|
|
|
|
};
|
2016-08-21 03:52:14 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|