做单元测试时应该考虑什么?

What should I consider when doing unit tests?

进行单元测试时应该考虑什么?什么步骤?什么情况?每个功能有多少测试?等等

我也很想了解有关您的体验的信息。我也在使用 laravel phpunit。我做了一个例子,它起作用了:

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

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

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

例如,您可以测试某些 post 表单的输入验证:

   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();
}

还可以测试你的listing信息,分页等等很多情况 你可以找到像错误一样的东西。 其实这个洞的概念就是对于每一个bug你都应该写新的测试!

根据这个例子(来自Lumen编程指南): 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 测试,但它们不是,因为它们是白盒测试(直接操作 DB)。