php - 伪造 JSON 数据的最佳实践 Laravel 5.2
问题描述
嗨,我正在为我用 Laravel 构建的一个小型 API 编写测试。我有数据通过前端的 axios 发布请求进入 API,我正在使用以下内容伪造数据。
public function test_that_the_form_json_data_structure_is_correct()
{
$lead = [
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'johndoe@example.com',
'phone' => '000-000-0000',
'street_address' => '123 Main Street',
'city' => 'CityA',
'state' => 'ZZ',
'zip' => '928171',
'spouse' => [
'name' => 'Sarah Aims',
'email' => 'sarahaims@example.com',
'phone' => '000-000-0000',
]
];
$quote = [
'address_is_same' => 1,
'property_street' => '123 Main Street',
'property_city' => 'CityA',
'property_state' => 'ZZ',
'property_zip' => '928171',
'primary_residence' => 1,
'secondary_residence' => 0,
'rental_property' => 0,
'number_of_units' => 2,
'losses' => 0,
'explain' => 'Some explaination here...',
'additional_comments' => 'Additional comments here...'
];
$this->json('POST', '/get-a-quote/home', [
'data' => [
'lead' => $lead,
'quote' => $quote
]
])->seeJsonStructure([
'lead_id',
'quote_id'
]);
}
我意识到我需要在多个测试中为我在前端拥有的不同形式编写该 $lead 数组变量。我知道 Laravel 中的模型工厂是专门为类设计的,所以我想知道处理与您的模型格式不同的 JSON 数据的最佳实践是什么,以及如何最好地测试它。我想我需要测试你在上面看到的实际数据,然后为 API 编写一个测试,看看它对传入数据的作用,即。创建模型等
解决方案
好吧,您的测试就像您的正常代码库一样。DRY 原则仍然适用。
所以我想建议先使用 Laravel工厂。例如,我猜你的$lead
变量是一个User
模型,在这种情况下你可以这样做:
$lead = factory(User::class)->make()->toArray()
这将返回一个完整的User
模型作为一个数组。
但你说:
使用与您的模型格式不同的 JSON 数据
所以在那种情况下,我只会在我的测试中有助手。如果您需要在任何地方使用它,您甚至可以使用静态方法创建一个完全返回数据的类,然后您可以更改您需要在测试中更改的字段。
推荐阅读
- node.js - 如何组合没有相互引用的 MongoDB 集合?
- bash - 关于正则表达式和通配符和 grep 的问题
- python - 如何将网站证书添加到 Python webscraper 的 Linux Docker 容器?
- asp.net-core - Blazor 服务器在仅使用 Windows 身份验证使用同源 Web API 时身份验证失败 - 401 Unauthorized
- php - 如何使用 Google My Business PHP 库更新现有位置?
- flutter - 在 Flutter 应用中检查设备是否兼容 NFC
- r - 通过拆分数据框映射函数时,“闭包”类型的对象不是子集错误
- kubernetes - 如何在 k8s 分支集群上运行 alertmanager
- javascript - 对文件使用 JavaScript
- prometheus - 解决第一次事件后如何让 Prometheus 发出警报?