用PHPUnit进行的流明测试仅通过2个测试就显示了过多的断言

问题描述 投票:0回答:1

我的测试工作正常,但是当我读到此article时,它是提到的

每个测试方法一个断言

而且我认为我的测试提出了太多的断言,这是我的测试代码:

<?php

use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;

class GuestTest extends TestCase
{
    use DatabaseTransactions;

    /** @test */
    public function guest_can_register()
    {
        $response = $this->json('POST', '/register', [
            "name" => "Khrisna Gunanasurya",
            "email" => "[email protected]",
            "password" => "adminadmin",
            "password_confirmation" => "adminadmin"
        ]);

        $response
                ->seeStatusCode(HttpStatus::$CREATED)
                ->seeJsonStructure([
                    "data" => [
                        "type",
                        "id",
                        "attributes" => [
                            'name',
                            'email'
                        ]
                    ]
                ]);
    }

    /** @test */
    public function registered_guest_can_login()
    {
        $this->post('/register', [
            "name" => "Khrisna Gunanasurya",
            "email" => "[email protected]",
            "password" => "adminadmin",
            "password_confirmation" => "adminadmin"
        ]);

        $response = $this->json('POST', '/login', [
            'email' => '[email protected]',
            'password' => 'adminadmin'
        ]);

        $response
                ->seeStatusCode(HttpStatus::$OK)
                ->seeJsonStructure([
                    'data' => [
                        'type',
                        'attributes' => [
                            'token',
                            'token_type',
                            'expires_in'
                        ]
                    ]
                ]);
    }
}

所以我想问的是,对于那些简单的测试,我的测试是否返回了太多的断言?因为我意识到seeJsonStructure()正在调用许多断言取决于嵌套的数组结构,并且如果我的测试单元进行过多的断言,将来在有大量测试文件时会产生问题吗?

编辑

enter image description here

php unit-testing phpunit lumen
1个回答
0
投票

如果您查看assertJsonStructure的内容,您将看到此函数的工作原理,它基本上遍历所有键并针对响应断言。所以在这种情况下

public function assertJsonStructure(array $structure = null, $responseData = null){
    foreach ($structure as $key => $value) {
        if (is_array($value)) {
            PHPUnit::assertArrayHasKey($key, $responseData);
            $this->assertJsonStructure($structure[$key], $responseData[$key]);
        } else {
            PHPUnit::assertArrayHasKey($value, $responseData);
        }
    }
}

因此,您有6个断言,它们由assertJsonStructure生成,另外一个由seeStatusCode生成。这将是总共7个断言,您有两个测试的总和为14。

© www.soinside.com 2019 - 2024. All rights reserved.