Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setUp/tearDown fixtures when unit testing in Laravel

I'm trying to write a unit test that checks attribute method that uses base_path() helper, however, I'm getting an exception: Call to undefined method Illuminate\Container\Container::basePath().

The full stacktrace is below:

\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php:179
\app\Message.php:47
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:432
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:333
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:306
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1279
\tests\Unit\MessageTest.php:59

I've tracked it down to using setUp and tearDown fixtures - even if I've got:

public function setUp()
{
    //$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__) . "/../..";
}

public function tearDown()
{
    //unset($_SERVER['DOCUMENT_ROOT']);
}

I'm getting the abovementioned error. If I remove the fixtures entirely, the error goes away.

After I've replaced the given methods with setUpBeforeClass and tearDownAfterClass the error goes away, but I'd like to know what is causing it.

As far as I'm aware of this is vanilla Laravel 5.4 installation (5.4.36 exactly), but it has additional libraries installed (and I'm not really able to say what libraries). I've not setup the phpunit.xml file, but to be fair I'd not know what to look for.

I've tested it with fresh installation of Laravel (same version) and it does happen straight out of the box (with untouched phpunit.xml file); on version 5.5 it doesn't.

like image 878
eithed Avatar asked Oct 28 '25 12:10

eithed


2 Answers

Try calling the parent class setUp and tearDown methods inside your own.

Like so:

public function setUp()
{
    parent::setUp();
    //$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__) . "/../..";
}

public function tearDown()
{
    parent::tearDown();
    //unset($_SERVER['DOCUMENT_ROOT']);
}
like image 75
Odd-Arne Johansen Avatar answered Oct 30 '25 02:10

Odd-Arne Johansen


Make sure that you are calling the parent setUp() and tearDown() first before you continue down. See code down here

public function setUp()
{
    parent::setUp();
    //$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__) . "/../..";
}

public function tearDown()
{
    parent::tearDown();
    //unset($_SERVER['DOCUMENT_ROOT']);
}
like image 37
WilliamDk Avatar answered Oct 30 '25 03:10

WilliamDk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!