@
@
@Twitt2018-05-07 19:21:00
Yii
@Twitt, 2018-05-07 19:21:00

How to make a unit test of methods in which one of the arguments is Yii::$app->user->identity->id?

There is a piece of old code:

public static function subscribe($id) { // Нажата кнопка подписки
            if (Relation::findSubscribe($id)) {
                $relation = new Relation();
                $relation->first_id = Yii::$app->user->identity->id;
                $relation->second_id = $id;
                $relation->type = 1; // тип 1 - подписка
                return $relation->save();
            } else {
                return null;
            }
        }
   }

I want to make a unit test for it (and I just started getting acquainted with them today), I planned to do this:
public function testSubscribe()
    {
        $this->assertNull(\app\models\Relation::subscribe(2));
    }

But it threw an error and I can't figure out what would be the correct code for the subscribe method unit test? Even if we pass an arbitrary first parameter, the second parameter is Yii::$app->user->identity->id, which in my opinion complicates the process, because the ID may be unknown.
By the way, the error is this:
Test tests\unit\RelationTest.php:testSubscribe
[yii\base\ErrorException] Trying to get property of non-object

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-05-08
@qonand

Well, there are two options here:
1. Either at the test level, create a User object with all the relevant information and replace it in the application
2. Or pass the user ID to the object in the constructor / when calling the
PS method, but in general, as if the code should not be tied to Yii: :$app->user and other detailed stuff...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question