Julien
Julien

Reputation: 31

Config class not found when unit testing laravel package

I'm working on a Laravel (5.4) package, and I'm trying to do unit testing. I have this class :

<?php

namespace Sample;

class Foo
{
    public function getConfig()
    {
        $config = \Config::get('test');

        return $config;
    }   
}

I have this test :

<?php

use PHPUnit\Framework\TestCase;
use Sample\Foo;

class FooTest extends TestCase
{
    public function testGetConfig()
    {
        $foo = new Foo;
        $config = $foo->getConfig();
    }
}

When I execute phpunit I have this error :

Error: Class 'Config' not found

How can I unit test this class ?

Thank you.

Upvotes: 3

Views: 3819

Answers (4)

sajed zarrinpour
sajed zarrinpour

Reputation: 1224

I had the same problem, and yes the answers are working, now here is the problem, what if I am developing a package and using pest to test it?

I solved the problem by adding this entry

uses(
    Tests\TestCase::class,
)->in('Unit', 'Feature', '../packages/vendor/package-name/tests/Unit');

to the

tests/Pest.php

hope this will help someone.

Upvotes: 1

pht
pht

Reputation: 91

Instead of extends PHPUnit\Framework\TestCase, you should extends Tests\TestCase:

<?php
namespace Tests\Unit;

// use PHPUnit\Framework\TestCase;
use Tests\TestCase;
use Sample\Foo;

class FooTest extends TestCase
{
    public function testGetConfig()
    {
        $foo = new Foo;
        $config = $foo->getConfig();
    }
}

Moreover, Config or other Laravel facades may not work in @dataProvider method, please see Laravel framework classes not available in PHPUnit data provider for more info.

Upvotes: 5

redcenter
redcenter

Reputation: 846

It is good practice to mock the dependencies in your code. In this case you are depending on an outside class (Config). Usually I test it like this:

// make sure the mock config facade receives the request and returns something
Config::shouldReceive('get')->with('test')->once()->andReturn('bla');

// check if the value is returned by your getConfig().
$this->assertEquals('bla', $config);

Obviously, you need to import the Config facade in your test.

BUT: I would inject the Config class in the constructor in my real code, instead of using the facade. But that's me... :-)

Something like this

class Foo
{
    /** container for injection */
    private $config;

    public function __construct(Config config) {
        $this->config = $config;
    }

    public function getConfig()
    {
        $config = $this->config->get('test');

        return $config;
    }   
}

And then test it by injecting a mock Config into the constructor.

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

Try by including like this

use Illuminate\Support\Facades\Config;

Upvotes: 0

Related Questions