Laravel 單元測試實戰(3)- 編寫整合測試確保介面和資料庫程式碼正確

yyy123456發表於2022-09-23

Laravel 單元測試實戰(3)- 編寫整合測試確保介面和資料庫程式碼正確

github 專案地址

git clone https://gitee.com/three_kingdoms_of_zhang/unit_test_practice.git
composer install
git checkout v3.0

程式碼是完整的,包括遷移,模型類,和全部功能。

最後編寫一個整合測試程式碼,對資料庫連線和控制器程式碼和 service 程式碼一起測試

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\DatabaseTestCase;
use Tests\TestCase;

class OrderControllerTest extends DatabaseTestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->postJson('/api/find_user_coupon', [
            'user_id' =>1,
            'shopping_cart'=>[
                [
                    'goods_id' => 1,
                    'count' => 3,
                ],
                [
                    'goods_id' => 2,
                    'count' => 1,
                ],
                [
                    'goods_id' => 3,
                    'count' => 2,
                ],
            ],
        ]);

        $response->assertStatus(200);
        $data = $response->getContent();
        $data = json_decode($data,1);
        $result = $data['data'];

        $result_expect = [
            'saved_money' =>11,
            'user_coupon_record'=>[
                'id' => 4,
                'type' => 2,
                'coupon_value' => 0.9,
                'condition_money' => 50,
            ],
        ];
        $this->assertEqualsWithDelta($result['saved_money'], $result_expect['saved_money'],0.02);
        $this->assertEquals($result['user_coupon_record']['id'], $result_expect['user_coupon_record']['id']);



    }

    public function get_table_datas()
    {
        return <<<sql
goods:
  -
    id: 1
    goods_name: "商品1"
    price: 10
  -
    id: 2
    goods_name: "商品2"
    price: 20
  -
    id: 3
    goods_name: "商品3"
    price: 30

user_coupons:
  -
    id: 1
    type: 1
    coupon_value: 5
    coupon_name: "優惠券1"
    condition_money: 1000
    use_status: 0
    user_id: 1
  -
    id: 2
    type: 1
    coupon_value: 5
    coupon_name: "優惠券2"
    condition_money: 50
    use_status: 0
    user_id: 1    
  -
    id: 4
    type: 2
    coupon_value: 0.9
    coupon_name: "優惠券4"
    condition_money: 50
    use_status: 0
    user_id: 1    
  -
    id: 5
    type: 1
    coupon_value: 6
    coupon_name: "優惠券5"
    condition_money: 50
    use_status: 0
    user_id: 1    

sql;

    }
}

執行整合測試

./vendor/bin/phpunit ./tests/Feature/OrderControllerTest.php

會顯示測試透過。

總結:

補齊整合測試。帶上資料庫,徹底驗證介面的正確性。
最後,該程式還有未驗證入參的問題,還有,單元測試應該多搞幾套資料,測試各種情況。包括邊界條件等。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章