PHPUnit: "Class 'Eloquent' not found" when using @dataProvider

I'm having this exact issue. It has to do with the fact that the Laravel aliases (e.g. Config::, Log::...) have not been loaded at the time that the @dataProvider method is called. There are two solutions here that I can think of here.

Solution 1

Modify your @dataProvider so that it doesn't use the model class. In my case, I was creating model objects in the @dataProvider method, like this:

public function people() {
    $person1 = new Person();
    $person1->name = "me";

    $person2 = new Person();
    $person2->name = "you";

    return [$person1, $person2];
}

Since the Person class is referenced in the @dataProvider method, it's going to attempt to load that class. Then it will fail because the Eloquent class alias hasn't been created by Laravel yet.

To get around this, I could just return the data, and create the actual model objects in the test itself:

public function people() {
    return ["me", "you"];
}

public function testPerson($name) {
    $person = new Person();
    $person->name = $name;

    // Assertions...
}

In your case, that would mean returning [['true']], instead of [[ExampleClass::TRUE]].

Solution 2

I see no compelling reason to use the Eloquent class alias here. In fact, I don't know why it exists at all (except perhaps that it "looks" better?). I brought this up in the IRC channel, and didn't get a response... So if there's a reason to use the alias here, then I don't know it.

That said, if your model class extends the underlying \Illuminate\Database\Eloquent\Model class instead of the Eloquent alias, then your tests will start working as-is.

<?php
namespace Acme\Models;

use \Illuminate\Database\Eloquent\Model;

class ExampleClass extends Model
{
    /**
     * @var bool
     */
    const TRUE = true;
}