为什么我不能在Laravel中创建Mock

时间:2019-07-09 17:45:32

标签: laravel unit-testing mockery

最近,我从事PHP Laravel中的单元测试。我在测试中是一个新手,但我通常会阅读有关应如何制作的信息……但实际上我无法正确编写它。仍然有一些错误。这是我要测试的类(方法)(模拟):

class ApiHelper
{
    private $model_locations;

    public function __construct($model_locations)
    {
        $this->model_locations = $model_locations;
    }

    public function calcAllDistances(string $location)
    {
        $request_data = $this->validLatLong($location);
        if(!$request_data) {
            return null;
        }
        $user_lat = $request_data[0];
        $user_lng = $request_data[1];
        $all_locations = $this->model_locations::all()->toArray();
        $all_distances = [];

        foreach($all_locations as $single_location) {
            $point = new \stdClass;
            $point_lat = $single_location['lat'];
            $point_lng = $single_location['lng'];
            $distance = $this->calcDistance($user_lat,$user_lng,$point_lat,$point_lng);
            $point->name = $single_location['name'];
            $point->lat = $point_lat;
            $point->lng = $point_lng;
            $point->distance = $distance;
            array_push($all_distances,$point);
        }

        return $all_distances;
    }

我们嘲笑calcAllDistances()方法。

这是我的测试示例;

public function testCalcAllDistances()
{
    $double = Mockery::mock(Locations::class)->shouldReceive('all')->with('')->andReturn(5)->getMock();
    $this->app->instance('App\Locations', $double);
    $object_under_tests = new \App\Helpers\ApiHelper($double);

    $result = $object_under_tests->calcAllDistances('21.132312,21.132312');

    $expected_result = [2.3, 4.7, 8.9];

    $this->assertEquals($expected_result, $result);
}

无论如何,我仍然会遇到类似这样的错误:

1) Tests\Unit\ApiHelper::testCalcAllDistances
Mockery\Exception\BadMethodCallException: Static method Mockery_0_App_Locations::all() does not exist on this mock object

D:\xampp4\htdocs\api\api\app\Helpers\ApiHelper.php:26
D:\xampp4\htdocs\api\api\tests\Unit\ApiHelperTest.php:41

Caused by
Mockery\Exception\BadMethodCallException: Received Mockery_0_App_Locations::all(), but no expectations were specified

我发誓,尝试了互联网上的所有内容...。但是我仍然无法编写测试。基本上,我想模拟Eloquent方法all()以返回我给定的值,以使calcAllDistances()方法正常工作。尝试了很多,makePartial()等,但是没有任何帮助。 非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您正在尝试模拟静态方法,但是您编写的代码却模拟了公共方法。 This answer包含了您要寻找的模拟方法。

作为一个旁注,由于诸如模拟静态方法之类的问题,不建议为Eloquent模型编写单元测试。 Laravel建议改写database tests。这些将为临时数据库提供测试所需的模型(以牺牲一些性能为代价)。