How mock logged in user in unit tests?

(Blaces) #1


I have a unit test class, but I need to “login the user”, because in the tested class, I get the logged in user’s email and id to generate a hash.

class AccountImageComponentTest extends DbTestCase


    use Specify;

    public function setUp()



        Yii::configure(Yii::$app, [

            'components' => [

                'user' => [

                    'class' => 'yii\web\User',

                    'identityClass' => 'common\models\User',




        //$model = new LoginForm([

        //    'username' => 'bayer.hudson',

        //    'password' => 'password_0',




    protected function tearDown()





    public function testGetPath() {

        $component = new AccountImageComponent();

        expect('path should be correct', $component->getPath())->equals('path');


    public function fixtures()


        return [

            'user' => [

                'class' => UserFixture::className(),

                'dataFile' => '@tests/codeception/frontend/unit/fixtures/data/models/user.php',




The $component->getPath() uses the logged in user’s data. But I do not know how I can load in the user.

I’ve tried to use the LoginFrom as you can see in the commented lines in setUp() method.

But those loginForm do not work, it gives this error always:


TypeError: Argument 1 passed to PHPUnit_Framework_TestCase::onNotSuccessfulTest() must be an instance of Exception, instance of Error given, called in /home/******/.composer/vendor/phpunit/phpunit/src/Framework/TestCase.php on line 851

And I do not understand this error.

Does somebody know how to mock the logged in user?