【问题标题】:How can I test an eloquent model method which calls a static method on the same class using Laravel 5.1, Phpunit and Mockery?如何使用 Laravel 5.1、Phpunit 和 Mockery 测试在同一类上调用静态方法的雄辩模型方法?
【发布时间】:2016-01-28 02:28:29
【问题描述】:

我有一个类,我正在尝试测试其中一种方法,但其中一种方法调用了同一个类的静态方法。我想知道如何在没有静态方法的情况下测试第一个方法并存根,以便我只测试第一个?

这里以一个愚蠢的类为例。

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

这是我尝试过的测试:

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

目前,测试返回“无法加载模拟 App\MyEloquentModel,类已存在”

【问题讨论】:

    标签: phpunit laravel-5.1 mockery


    【解决方案1】:

    你可以这样做:

    class MyEloquentModelTest extends TestCase 
    { 
        public function test_foo_method_returns_correct_value() 
        { 
            // Mock class 
            $my_mocked_eloquent_model = Mockery::mock('App\MyEloquentModel[bar]');
            $my_mocked_eloquent_model->shouldReceive('bar') 
                ->once() 
                ->with('hello') 
                ->andReturn('world');
    
        $this->assertEquals("hello world", $my_mocked_eloquent_model->foo('hello'));
        }
    }
    

    这创建为 MyEloquentModel 类的部分模拟,其中只有方法“bar”被模拟。在 shouldReceive 方法中应该指定要模拟的方法,而不是方法的参数(如您指定的那样)。对于 with 方法,您应该指定您希望将哪些参数提供给该方法。

    您收到“无法加载模拟 App\MyEloquentModel,类已存在”的错误很可能是因为您首先为 MyEloquentModel 类指定了一个模拟,然后尝试使用 new MyEloquentModel; 创建该类的新实例。正如您在我的回复中看到的那样,您不应该创建该类的新实例,而是创建一个模拟,您将使用它来调用您想要测试的方法。

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 2021-03-12
      • 2016-06-24
      • 2014-08-16
      • 2014-02-08
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多