【问题标题】:Best Practice for Faking JSON Data Laravel 5.2伪造 JSON 数据的最佳实践 Laravel 5.2
【发布时间】:2018-11-15 05:42:57
【问题描述】:

您好,我正在为使用 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 编写一个测试,看看它对传入数据的作用,即。创建模型等。

【问题讨论】:

    标签: php laravel phpunit


    【解决方案1】:

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

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

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

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

    但你说:

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

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

    【讨论】:

    • 好吧,我就是这么想的。使用静态方法创建辅助类。是的,数据的格式不一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多