Laravel Collection macro not found in phpunit unit test?

59 views Asked by At

I'm running a unit test in Laravel in phpunit and encountering this error where my Collection macro seemingly does not exist:

Method Illuminate\Support\Collection::getNext does not exist.

The code itself works absolutely fine in the project, though! The line which fails here has been exercised in "production" a whole lot and is without issue. This problem only seems to exist when testing with phpunit.

Here's where I define the macro:

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        /**
         * Returns the next found item in the collection after the given index value
         */
        Collection::macro('getNext', function ($currentIndex) {
            return $this->get($currentIndex + 1, null);
        });
    }
}

And the test code:

namespace Tests\Feature;
use App\src\LineProcessLibrary;
use PHPUnit\Framework\TestCase;
use Illuminate\Support\Collection;

class LineProcessLibraryTest extends TestCase
{
    public function test_process_stuff(): void
    {
        $input = [
            ['text' => 'This line continues,', 'start' => 10, 'end' => 12]
        ];

        $res = LineProcessLibrary::processStuff($input);
    }

And the actual code being invoked:

namespace App\src;
use Illuminate\Support\Collection;

class LineProcessLibrary
{
    public static function processStuff($list)
    {
        $stuff = collect($list);
        foreach ($stuff as $key => $curr) {

            $next = $stuff->getNext($key);
            dd($next);
        }
    }

So far I've tried moving the test to the Feature folder and namespace in the hope that stuff there has more app related classes automatically loaded (including hopefully my macro). No luck so far.

This really seems like the sort of thing that could be a common issue or should really have a simple, well-known fix but so far I can't find it.

1

There are 1 answers

3
suxgri On

Laravel docs says:

Typically, you should declare collection macros in the boot method of a service provider.

So i would move the the macro from register to boot