How to mock ActiveRecord


(Alexander Makarov) #1

If you want to mock AR that doesn’t try to connect to database you can do it in the following way (if using PHPUnit):

$post = $this->getMockBuilder('\app\model\Post')
    ->setMethods(['save', 'attributes'])
    ->getMock();

$post->method('save')->willReturn(true);
$post->method('attributes')->willReturn([
    'id',
    'status',
    'title',
    'description',
    'text'
]);

The catch is that we need to override attributes() method since ActiveRecord by default is getting attributes list from database schema which we’re trying to avoid.