【问题标题】:Why I can't create Mock in Laravel为什么我不能在 Laravel 中创建 Mock
【发布时间】:2019-11-19 08:02:55
【问题描述】:

最后几天我在 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() 等,但没有任何帮助。 非常感谢您的帮助

【问题讨论】:

    标签: laravel unit-testing mockery


    【解决方案1】:

    您正在尝试模拟静态方法,但您编写的代码正在模拟公共方法。 This answer 包含你正在寻找的嘲笑方式。

    顺便说一句,由于模拟静态方法等问题,不鼓励为 Eloquent 模型编写单元测试。 Laravel 建议改用 database tests。这些将使用您的测试所需的模型为一个临时数据库播种(以牺牲一些性能为代价)。

    【讨论】:

      猜你喜欢
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2020-09-21
      • 2014-08-15
      • 2019-07-01
      • 2013-03-30
      • 2015-01-25
      相关资源
      最近更新 更多