其实我们这样子写的方式,
感觉有点像在呼叫API,
所以我们决定要把它改成放到API,
我们把原本在web.php的内容删掉,
然後新增一个APIController
php artisan make:controller API/APIController
档案内容如下:
<?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
可以成功通过测资了。
<<: Day 10:让你见识我的一小部分力量,Ktor的网路请求
>>: 【Day15】公园跟你家院子—全域变数与区域变数的区别
Salom,我是Charlie! 在Day20的时候我们完成了createOrder跟Capture...
正文 今天来把昨天写的页面进行容器化的动作,首先撰写Dockerfile # static buil...
没有人是一座孤岛,而技术与软件亦然。早在 Hoddarla 抵达系列文本篇最後的基本命令列功能之前、...
今天开始,我们要进入物件导向的世界了,先前已经简单提过了,物件导向程序设计是一种以物件观念来设计程序...
前言 今天是铁人赛的第十五天,终於要把前两天的爬虫程序整合到LineBot了 再次说明:这里不是手把...