【问题标题】:What should I consider when doing unit tests?进行单元测试时应该考虑什么?
【发布时间】:2017-05-17 18:39:12
【问题描述】:

进行单元测试时我应该考虑什么?有哪些步骤?什么情况?每个函数有多少测试?等等

我也希望能提供有关您体验的信息。我也在使用 laravel phpunit。我做了一个例子,它奏效了:

public function test_for_clientUser() {
    $this->json('POST', 'clientUser', ['id'=>'232421'])->seeJsonStructure([[]]);
}

我发送一个带有 id 的请求,它返回一个数组。您还为这个测试添加了哪些产品?

【问题讨论】:

  • 测试应该检查您的假设结果,而不是检索数据。您假设响应将是一个 json 结构,或者响应将是成功的。您不检查响应的具体内容。您测试的是逻辑,而不是数据。更多关于 Laravel 测试的信息可以在here找到。

标签: php laravel unit-testing phpunit lumen


【解决方案1】:

您可以为每个控制器将测试分成几个操作(列表、存储、显示、更新、删除等)。

例如,您可以测试一些帖子表单的输入验证:

   public function testStoringCityAsOwnerWithNotExistingCountryId()
{
    $input = [
        'country_id' => 0,
        'translations' => [
            [
                'name' => 'Варна',
                'lang' => 'bg'
            ]
        ]
    ];

    $response = [
        'errors' => [
            'country_id' => [
                trans(
                    'validation.exists',
                    ['attribute' => 'country id']
                )
            ]
        ]
    ];

    $this->asOwner()
        ->post('/cities', $input, $this->headers)
        ->seeStatusCode(ResponseCode::PERMISSIONS_DENIED)
        ->dontSeeJson();
}

您还可以测试您的列表信息、分页和许多其他情况 你可以找到类似的错误。 实际上漏洞的概念是,你应该为每个错误编写新的测试!

【讨论】:

    【解决方案2】:

    根据这个例子(来自 Lumen Programming Guide): https://github.com/Apress/lumen-programming-guide/blob/master/tests/app/Http/Controllers/BooksControllerTest.php

    你或多或少会测试这个:

    GET /index
        - status code is 200
        - returns a collection of (well-formed) records
    
    GET /show
        - status code is 200
        - returns a valid (well-formed) resource 
        - should fail with a non existing id (404)
        - should not respond with 200 if id is not numeric. Maybe 404
    
    POST /store
        - the resource stores in DB
        - returns code 201 CREATED
        - returns a valid json qith a resource id
    
    PUT /update
        - status code is 204
        - the resource has not the new value in DB
        - the resource now has updated data in DB
        - modified date was updated
        - should fail with a non existing id (404)
        - should not respond with 204 if id is not numeric. Maybe 404
    
    DELETE /destroy
        - returns 204
        - should fail with a non existing id (404)
        - should not respond with 204 if id is not numeric. Maybe 404
    

    当您修改数据库时(而不应该是测试数据库,例如在内存上运行的 SQLite 实例),这些不是统一的,但可能是功能性的。我不能保证。作者称它们为 acceptance 测试,但它们不是,因为它们是白盒测试(直接操作数据库)。

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2021-09-05
      • 2016-05-31
      • 2013-10-13
      • 2016-10-13
      • 2012-06-15
      • 2010-09-08
      • 2011-02-14
      • 1970-01-01
      相关资源
      最近更新 更多