[Day 23] 针对API的单元测试(三)

我们今天来针对API做更进一步的测试,
假如我们今天要取得一个使用者资料,
这个使用者的资料有 代号(id)、姓名(name)、电话(phone)
我们现在在MyFirstUnitTest.php写了一个新的方法

public function test_user_get_name()
{
    $this->post('/api/user/1')
        ->assertJson(fn (AssertableJson $json) =>
            $json->where('id', 1)
                ->where('name', '小鱼')
                ->missing('password')
                ->etc()
        );
}

我们指定了id跟name参数的内容,
并且不应该出现password这个参数,
後面有一个etc()表示我们忽略其他的参数,
如果回传的资料有其他的参数,
但是我们没有调用etc()方法的话,
我们的测试将会失败。

然後我们来测试看看
php artisan test
https://ithelp.ithome.com.tw/upload/images/20210924/20105694Szj8Ely6rB.png

结果是找不到这个路由,
因为我们还没有实作,
接下来我们新增一个Model
App\Entity\User.php

<?PHP
namespace App\Entity;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    //资料表名称
    protected $table = 'user';

    //主键名称
    protected $promaryKey = 'id';

    //可以大量指定异动的栏位(Mass Assignment)
    protected $fillable = [
            'name',
            'phont',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
?>

然後我们在APIController.php新增一个方法,
正常来说我们会去捞资料库的资料,
或是其他的方式,
不过在这里我们直接把结果回传,
当然要记得引用 use App\Entity\User;

function GetUser($id)
{
    $result = new User;

    if($id == 1)
    {
        $result->id = 1;
        $result->name = '小鱼';
        $result->phone = '7533967';
    }

    return json_encode($result);
}

然後在api.php新增路由

Route::group(['prefix' =>'user'], function(){
    Route::post('/{id}', [APIController::class, 'GetUser']);
});

我们再测试看看
php artisan test
https://ithelp.ithome.com.tw/upload/images/20210924/20105694C1avjIEbmQ.png

顺利地通过测试了!


<<:  Angular RxJs 各种解订阅方式

>>:  前端工程师也能开发全端网页:挑战 30 天用 React 加上 Firebase 打造社群网站|Day24 修改会员密码

消息身份验证代码(message authentication code)

-CBC-MAC(来源:https : //en.wikipedia.org/wiki/CBC-M...

【把玩Azure DevOps】Day1 前言

光阴似箭,岁月如梭…呃…不是…,我是要说离我前一次报名参加铁人赛已经间隔了8年… 又是一个去年原本看...

[Day25] - Django-REST-Framework Authencation Permission 介绍

今天我们来介绍 DRF 的 Authentication,了解 DRF 如何加入 Authencat...

[Day 23] 从GEIT制定管理规范

这个章节很多都在CISSP有,很多邦友写过,可以参考邦友的文章 https://ithelp.ith...

应用系统的防护基准 - 委外注意事项

这年头要赚政府的钱也不容易啊 资安法要求的对象不只有公务机关,连委外的厂商也需要符合大部分的应办事项...