mercredi 28 octobre 2015

How can I test an eloquent model method which calls a static method on the same class using Laravel 5.1, Phpunit and Mockery?

I have a class, and I'm trying to test one of it's methods but one of the methods calls a static method on the same class. I'm wondering how to test the first method without and stub the static method so that I'm only testing the first?

Here's a silly class as an example.

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"; 
        }
    }
}

Here's the test I've tried:

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"



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire