Unable to use Yii::error() log methods from unit tests

I’m trying to use methods like Yii::error() or Yii::warning() from inside a unit test. Whenever I try though I get a Fatal Error:

PHP Fatal error: Call to a member function getRequest() on a non-object in /myapp/vendor/yiisoft/yii2/log/Target.php on line 269

It seems that Yii::$app is not set/available in that function. These methods work properly when used in a web/browser context, but not within unit tests. Is anyone logging from within unit tests? Does it require any special configuration?

You have to setup a Yii application first before running the test. If you are using codeception, you can use http://www.yiiframework.com/doc-2.0/yii-codeception-testcase.html#mockApplication()-detail or copy the code from that method into your own test class.

Thank you for your response CeBe. I went back and tried adding the call to mockApplication and then realized that already exists in yii\codeception\TestCase::setUp();

I’m trying to use a very basic unit test to debug, here is what I have:




namespace tests\codeception\unit\models;


use yii\codeception\TestCase;


class DummyTest extends TestCase

{

    protected function setUp()

    {

        parent::setUp();

    }


    public function testDummy() {

        \Yii::error("Error message");

        \Yii::warning("Warning message");

    }

}



Output shows:




$ php codecept.phar run --debug unit models/DummyTest.php

Codeception PHP Testing Framework v2.0.7

Powered by PHPUnit 4.3.4 by Sebastian Bergmann.


Unit Tests (1) -----------------------------------------------------------------------------------------------------------------

Modules: 

--------------------------------------------------------------------------------------------------------------------------------

Trying to test dummy (tests\codeception\unit\models\DummyTest::testDummy)                                                  Ok

--------------------------------------------------------------------------------------------------------------------------------


Time: 91 ms, Memory: 9.50Mb


OK (1 test, 0 assertions)

PHP Fatal error:  Call to a member function getRequest() on a non-object in /myapp/vendor/yiisoft/yii2/log/Target.php on line 269



Also just to give some more details, here is a gist of my composer.json and composer.lock so you can see versions.