Synchro's avatar

Loading app dependencies during unit test

I have a simple utility function that uses translation, along the lines of:

    public static function optionName(int $optionNumber): string
    {
        return match($optionNumber) {
            0 => __('Zero'),
            1 => __('One'),
        };
    }

When I try to run a unit test for this, like:

self::assertEquals('Zero', Utilities::optionName(0));

it fails saying:

Illuminate\Contracts\Container\BindingResolutionException : Target class [translator] does not exist.

I assume that since this is a simple standalone test, the app environment is not loaded and so the translation service isn't available from the service container, because there is no service container at this point. My test class is a straightforward extension of PHPUnit\Framework\TestCase.

How should I initialise the app environment from the test?

0 likes
3 replies
LaryAI's avatar
Level 58

To initialize the app environment from the test, you can use the RefreshDatabase trait provided by Laravel. This trait will refresh the database before each test and also boot the application environment. Here's an example of how you can use it:

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UtilitiesTest extends TestCase
{
    use RefreshDatabase;

    public function testOptionName()
    {
        $this->assertEquals('Zero', Utilities::optionName(0));
    }
}

By using the RefreshDatabase trait, you can ensure that the app environment is loaded and the translation service is available from the service container.

Synchro's avatar

@LaryAI Can I boot the app env without involving the DB? Bringing up the DB is hundreds of times slower, and the database is not needed for the test.

Synchro's avatar
Synchro
OP
Best Answer
Level 2

Switching the base test class from PHPUnit\Framework\TestCase to Tests\TestCase solved the problem; this base class includes the CreatesApplication and LazilyRefreshDatabase traits, and they appear to do what's needed, and the test runs in 0.2 sec.

Please or to participate in this conversation.