Как тестировать модели с BlameableBehavior

Всё про тестирование в Yii 2.0
Ответить
damasco
Сообщения: 8
Зарегистрирован: 2015.03.05, 06:21

Как тестировать модели с BlameableBehavior

Сообщение damasco »

Как писать unit test для модели у которого подключен BlameableBehavior?
Аватара пользователя
ElisDN
Сообщения: 5845
Зарегистрирован: 2012.10.07, 10:24
Контактная информация:

Re: Как тестировать модели с BlameableBehavior

Сообщение ElisDN »

damasco писал(а):Как писать unit test для модели у которого подключен BlameableBehavior?
Интеграционный:

Код: Выделить всё

public function testBlameable()
{
    Yii::$app->user->login(new User(['id' => 5]));
    $post = new Post();
    $post->save();
    $this->assertEquals(5, $post->author_id);
} 
Костыльная пародия на юнит-тест:

Код: Выделить всё

public function testBlameable()
{
    $user = $this->getMock('yii\web\User', ['getIsGuest', 'getId'])
    $user->method('getIsGuest')->willReturn(false);
    $user->method('getId')->willReturn(5);
    Yii::$app->set('user', $user);

    $post = $this->getMockBuilder('\app\model\Post') ->setMethods(['attributes']) ->getMock();
    $post->method('attributes')->willReturn(['id', 'title',  'author_id',  'text']);

    $post->beforeSave(true);

    $this->assertEquals(5, $post->author_id);
} 
Полноценный юнит-тест в рамках Yii2:

Код: Выделить всё

public function testBlameable()
{
    $user = $this->getMock('yii\web\User', ['getIsGuest', 'getId'])
    $user->method('getIsGuest')->willReturn(false);
    $user->method('getId')->willReturn(5);
    Yii::$app->set('user', $user);
    
    $schema =  $this->getMock('yii\db\Schema', ['insert', 'getTableSchema']);
    $schema->method('insert')->willReturn(['id' => 1]);        
    $schema->method('getTableSchema')->willReturn(new yii\db\TableSchema([
        'columns' => [
            'id' => new yii\db\ColumnSchema([
                'name' => 'id',
                'type' => 'integer',
                'phpType' => 'integer',
                'dbType' => 'int(11)',
                'size' => 11,
                'precision' => 11,
                'isPrimaryKey' => 1,
                'autoIncrement' => 1,
            ]),
            'author_id' => new yii\db\ColumnSchema([
                'name' => 'id',
                'type' => 'integer',
                'phpType' => 'integer',
                'dbType' => 'int(11)',
                'size' => 11,
                'precision' => 11,
                'isPrimaryKey' => 0,
                'autoIncrement' => 0,
            ]),
        ],
    ]);    
    $db =  $this->getMock('yii\db\Connection', ['getSchema']);
    $db->method('getSchema')->willReturn($schema);    
    Yii::$app->set('db', $db);

    $post = new Post();
    $post->save(false);

    $this->assertEquals(5, $post->author_id);
} 
damasco
Сообщения: 8
Зарегистрирован: 2015.03.05, 06:21

Re: Как тестировать модели с BlameableBehavior

Сообщение damasco »

Спасибо, за развернутый ответ.
Ответить