[Day 14] 简单的单元测试实作(八)-修改成API来呼叫

其实我们这样子写的方式,
感觉有点像在呼叫API,
所以我们决定要把它改成放到API,
我们把原本在web.php的内容删掉,
然後新增一个APIController
php artisan make:controller API/APIController
https://ithelp.ithome.com.tw/upload/images/20210915/20105694o0cblmp87Y.png

档案内容如下:

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;

class APIController extends Controller
{
    //
}

然後我们在routes/api.php新增

Route::post('/getLeapYear/{year}', 'Api\APIController@checkLeapYear');

这种呼叫方式是传统的方式,
但是Laravel 8不能直接这样子用,
通常是建议用以下的方式

use App\Http\Controllers\API\APIController;
Route::post('/getLeapYear/{year}', [APIController::class, 'checkLeapYear']);

关键在於这个档案
app/Providers/RouteServiceProvider.php
里面的第29行被注解掉了

// protected $namespace = 'App\\Http\\Controllers';

把这行注解拿掉就可以使用旧的方式来呼叫了,
不过比较不倾向用这种方式,
所以我们之後都使用呼叫class的方式来写.

然後我们在APIController.php里面加入函式去呼叫GetLeapYear这个函式

function checkLeapYear($year)
{
    $leap = GetLeapYear($year);
    if($leap)
        return "闰年";
    return "平年";
}

我们的测试程序也要改一下MyFirstUnitTest.php

<?php

namespace Tests\Feature;

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

class MyFirstUnitTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_example()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

    public function test_leapyear_return_200()
    {
        $response = $this->post('api/getLeapYear/0');

        $response->assertStatus(200);
    }

    /**
     * @param $input
     * @param $output
     * @dataProvider input_number
     */
    public function test_leapyear_check_year($input, $output)
    {
        $response = $this->post("api/getLeapYear/$input");
        $this->assertSame($output, $response->getContent());
    }

    public function input_number()
    {
        return [
            ['4', '闰年'],
            ['2020', '闰年'],
            ['1900', '平年'],
            ['2100', '平年'],
            ['2000', '闰年'],
            ['1600', '闰年'],
            ['2021', '平年'],
            ['2023', '平年'],
        ];
    }
}

然後我们执行测试程序
php vendor/phpunit/phpunit/phpunit tests/Feature/MyFirstUnitTest.php
https://ithelp.ithome.com.tw/upload/images/20210915/20105694ZKyfhjFFE8.png

可以成功通过测资了。


<<:  Day 10:让你见识我的一小部分力量,Ktor的网路请求

>>:  【Day15】公园跟你家院子—全域变数与区域变数的区别

Day21:21 - 结帐服务(5) - 後端 - 结帐 X PayPal Python Checkout SDK

Salom,我是Charlie! 在Day20的时候我们完成了createOrder跟Capture...

Day06,将昨日的静态页面打包

正文 今天来把昨天写的页面进行容器化的动作,首先撰写Dockerfile # static buil...

予焦啦!附录:那些作业系统的巨人们与参考资料

没有人是一座孤岛,而技术与软件亦然。早在 Hoddarla 抵达系列文本篇最後的基本命令列功能之前、...

[Day21] CH11:刘姥姥逛物件导向的世界——类别与物件

今天开始,我们要进入物件导向的世界了,先前已经简单提过了,物件导向程序设计是一种以物件观念来设计程序...

DAY15 - 第四个小范例 : Line股价机器人

前言 今天是铁人赛的第十五天,终於要把前两天的爬虫程序整合到LineBot了 再次说明:这里不是手把...