【发布时间】: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