首页 > 解决方案 > 伪造 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 编写一个测试,看看它对传入数据的作用,即。创建模型等

标签: phplaravelphpunit

解决方案


好吧,您的测试就像您的正常代码库一样。DRY 原则仍然适用。

所以我想建议先使用 Laravel工厂。例如,我猜你的$lead变量是一个User模型,在这种情况下你可以这样做:

$lead = factory(User::class)->make()->toArray()

这将返回一个完整的User模型作为一个数组。

但你说:

使用与您的模型格式不同的 JSON 数据

所以在那种情况下,我只会在我的测试中有助手。如果您需要在任何地方使用它,您甚至可以使用静态方法创建一个完全返回数据的类,然后您可以更改您需要在测试中更改的字段。


推荐阅读