WebSpanner's avatar

Best way to test an Eloquent model method which calls a static method on the same class?

Class:

class MyEloquentModel extends Model
{
    // Returns input concatenated with output of bar for that input
    public function foo($input) {
        $bar = MyEloquentModel::bar($input);
        return $input." ".$bar;
    }
    
    // Returns world if input received is hello
    public static function bar($input) {
        if ($input == "hello") {
            return "world"; 
        }
    }
}

Test:

class MyEloquentModelTest extends TestCase
{
    public function test_foo_method_returns_correct_value() {
        // Mock class
        $mock = \Mockery::mock('App\MyEloquentModel');
        $mock->shouldReceive('hello')
            ->once()
            ->with()
            ->andReturn('world');
            
        // Create object
        $my_eloquent_model = new MyEloquentModel;
        
        $this->assertTrue($my_eloquent_model->foo('hello') == "hello world");
    }
}

As it stands, the test returns "Could not load mock App\MyEloquentModel, class already exists"

0 likes
5 replies
monkeyslippery's avatar

Add this to your test class

/**
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */
JeffreyWay's avatar

There's no need to mock it.

class MyEloquentModelTest extends TestCase
{
    public function test_foo_method_returns_correct_value() 
    {
            $model = new MyEloquentModel;
            
            $this->assertEquals('hello world', $model->foo('hello'));
        }
    }
}
Tray2's avatar

@jeffreyway , that has been going on for a while now, maybe threads older than three months or somesuch should be locked from adding replies to.

1 like

Please or to participate in this conversation.