rest laravel_如何通过测试驱动开发来构建Laravel REST API
rest laravel
by Kofo Okesola
由Kofo Okesola
如何通過測(cè)試驅(qū)動(dòng)開發(fā)來構(gòu)建Laravel REST API (How to build a Laravel REST API with Test-Driven Development)
There is a famous quote by James Grenning, one of the pioneers in TDD and Agile development methodologies:
TDD和敏捷開發(fā)方法學(xué)的先驅(qū)之一James Grenning引用了著名的話:
If you’re not doing test-driven development, you’re doing debug-later development - James Grenning如果您不進(jìn)行測(cè)試驅(qū)動(dòng)的開發(fā),那么就在進(jìn)行后期調(diào)試-James GrenningToday we’ll be going on a Laravel journey driven by tests. We’ll create a Laravel REST API complete with authentication and CRUD functionality without opening Postman or a browser. ?
今天,我們將進(jìn)行由測(cè)試驅(qū)動(dòng)的Laravel之旅。 我們將創(chuàng)建具有身份驗(yàn)證和CRUD功能的Laravel REST API,而無需打開Postman或?yàn)g覽器。 ?
Note: This walkthrough assumes that you understand the basic concepts of Laravel and PHPUnit. If you’ve got that out of the way? Let’s drive.
注意:本演練假定您了解Laravel和PHPUnit的基本概念。 如果您不打算這么做? 開車吧
設(shè)置項(xiàng)目 (Setting up the project)
Start by creating a new Laravel project with composer create-project --prefer-dist laravel/laravel tdd-journey.
首先使用composer create-project --prefer-dist laravel/laravel tdd-journey創(chuàng)建一個(gè)新的Laravel項(xiàng)目。
Next, we need to run the authentication scaffolder that we would use, go ahead and run php artisan make:auth then php artisan migrate.
接下來,我們需要運(yùn)行將使用的身份驗(yàn)證支架,繼續(xù)運(yùn)行php artisan make:auth然后運(yùn)行php artisan make:auth php artisan migrate 。
We will not actually be using the routes and views generated. For this project, we would be using jwt-auth. So go ahead and set it up in your application.
我們實(shí)際上不會(huì)使用生成的路線和視圖。 對(duì)于此項(xiàng)目,我們將使用jwt-auth 。 所以,盡管設(shè)置它在你的應(yīng)用程序。
Note: If you’re having errors with JWT’s generate command, you can follow this fix till it’s been added to the stable release.
注意:如果您在JWT的generate命令上遇到錯(cuò)誤,則可以遵循此修補(bǔ)程序,直到將其添加到穩(wěn)定版本中為止。
Finally, you can delete ExampleTest in both the tests/Unit and tests/Feature folders so that it doesn’t interfere with our test results and we’re good to go.
最后,您可以在tests/Unit和tests/Feature文件夾中都刪除ExampleTest ,以免干擾我們的測(cè)試結(jié)果,我們一切順利。
編寫代碼 (Writing the code)
Begin by setting your auth configuration to use the JWT driver as default:
首先將您的auth配置設(shè)置為默認(rèn)使用JWT驅(qū)動(dòng)程序:
Then add the following to your routes/api.php file:
然后將以下內(nèi)容添加到您的routes/api.php文件中:
2. Now that we have our driver set up, set up your user model in the same way:
2.現(xiàn)在我們已經(jīng)設(shè)置了驅(qū)動(dòng)程序,以相同的方式設(shè)置您的用戶模型:
What we did was that we just implemented the JWTSubject and added the required methods.
我們所做的是,我們剛剛實(shí)現(xiàn)了JWTSubject并添加了所需的方法。
3. Next, we need to add our authentication methods in the controller.
3.接下來,我們需要在控制器中添加身份驗(yàn)證方法。
Run php artisan make:controller AuthController and add the following methods:
運(yùn)行php artisan make:controller AuthController并添加以下方法:
This step is pretty straight forward, all we do is add the authenticate and register methods to our controller. In the authenticate method, we validate the input, attempt a login and return the token if successful. In the register method, we validate the input, create a new user with the input and generate a token for the user based on that.
這一步很簡單,我們要做的就是向我們的控制器添加authenticate和register方法。 在authenticate方法中,我們驗(yàn)證輸入,嘗試登錄,如果成功,則返回令牌。 在register方法中,我們驗(yàn)證輸入,使用輸入創(chuàng)建新用戶,并基于該輸入為用戶生成令牌。
4. Next, onto the good part. Testing what we just wrote. Generate the test classes using php artisan make:test AuthTest. In the new tests/Feature/AuthTest add these methods:
4.接下來,進(jìn)入好部分。 測(cè)試我們剛剛寫的內(nèi)容。 使用php artisan make:test AuthTest生成測(cè)試類。 在新的tests/Feature/AuthTest添加以下方法:
The comments in the code above pretty much describes the code. One thing you should note is how we create and delete the user in each test. The whole point of tests are that they should be independent of each other and the database state ideally.
上面代碼中的注釋幾乎描述了該代碼。 您應(yīng)該注意的一件事是,我們?nèi)绾卧诿看螠y(cè)試中創(chuàng)建和刪除用戶。 測(cè)試的全部重點(diǎn)是它們應(yīng)該彼此獨(dú)立,并且理想情況下數(shù)據(jù)庫狀態(tài)應(yīng)獨(dú)立。
Now run $vendor/bin/phpunit or $ phpunit if you have it globally installed. Running that should give you successful assertions. If that was not the case, you can look through the logs, fix and retest. This is the beautiful cycle of TDD.
現(xiàn)在運(yùn)行$vendor/bin/phpunit或$ phpunit如果已全局安裝)。 運(yùn)行該命令將給您成功的斷言。 如果不是這種情況,您可以瀏覽日志,修復(fù)并重新測(cè)試。 這是TDD的美好周期。
5. Now that we have our authentication working, let’s add the item for the CRUD. For this tutorial, we’re going to use food recipes as our CRUD items, because, why not?
5.現(xiàn)在我們可以進(jìn)行身份??驗(yàn)證了,讓我們?yōu)镃RUD添加項(xiàng)目。 在本教程中,我們將使用食物食譜作為CRUD項(xiàng)目,因?yàn)闉槭裁床荒?#xff1f;
Start by creating our migration php artisan make:migration create_recipes_table and add the following:
首先創(chuàng)建我們的遷移php artisan make:migration create_recipes_table并添加以下內(nèi)容:
Then run the migration. Now add the model using php artisan make:model Recipe and add this to our model.
然后運(yùn)行遷移。 現(xiàn)在,使用php artisan make:model Recipe添加php artisan make:model Recipe ,并將其添加到我們的模型中。
Then add this method to the user model.
然后將此方法添加到user模型。
6. Now we need endpoints for managing our recipes. First, we’ll create the controller php artisan make:controller RecipeController. Next, edit the routes/api.php file and add the create endpoint.
6.現(xiàn)在我們需要用于管理配方的端點(diǎn)。 首先,我們將創(chuàng)建控制器php artisan make:controller RecipeController 。 接下來,編輯routes/api.php文件并添加create端點(diǎn)。
In the controller, add the create method as well
在控制器中,還添加create方法
Generate the feature test with php artisan make:test RecipeTest and edit the contents as under:
使用php artisan make:test RecipeTest生成功能測(cè)試, php artisan make:test RecipeTest編輯內(nèi)容:
The code is quite self-explanatory. All we do is create a method that handles the registering of a user and token generation, then we use that token in the testCreate() method. Note the use of the RefreshDatabase trait, the trait is Laravel’s convenient way of resetting your database after each test, which is perfect for our nifty little project.
該代碼是不言自明的。 我們要做的就是創(chuàng)建一個(gè)處理用戶注冊(cè)和令牌生成的方法,然后在testCreate()方法中使用該令牌。 請(qǐng)注意,使用了RefreshDatabase特性,該特性是Laravel在每次測(cè)試后重置數(shù)據(jù)庫的便捷方法,這對(duì)于我們漂亮的小項(xiàng)目是完美的。
OK, so for now, all we want to assert is the status of the response, go ahead and run $ vendor/bin/phpunit.
好的,現(xiàn)在,我們要斷言的只是響應(yīng)的狀態(tài),繼續(xù)運(yùn)行$ vendor/bin/phpunit 。
If all goes well, you should receive an error. ?
如果一切順利,您應(yīng)該會(huì)收到一個(gè)錯(cuò)誤消息。 ?
There was 1 failure:1) Tests\Feature\RecipeTest::testCreateExpected status code 200 but received 500.Failed asserting that false is true./home/user/sites/tdd-journey/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133/home/user/sites/tdd-journey/tests/Feature/RecipeTest.php:49FAILURES!Tests: 3, Assertions: 5, Failures: 1.Looking at the log files, we can see the culprit is the publisher and recipes relationship in the Recipe and User classes. Laravel tries to find a user_id column in the table and use that as the foreign key, but in our migration we set publisher_id as the foreign key. Now, adjust the lines as under:
查看日志文件,我們可以發(fā)現(xiàn)罪魁禍?zhǔn)资荝ecipe和User類中的publisher和recipes關(guān)系。 Laravel嘗試在表中查找user_id列并將其用作外鍵,但是在我們的遷移中,我們將publisher_id設(shè)置為外鍵。 現(xiàn)在,根據(jù)以下內(nèi)容調(diào)整行:
//Recipe filepublic function publisher(){ return $this->belongsTo(User::class,'publisher_id');}//User filepublic function recipes(){ return $this->hasMany(Recipe::class,'publisher_id');}And then re-run the test. If all goes well we get all green tests! ?
然后重新運(yùn)行測(cè)試。 如果一切順利,我們將獲得所有綠色測(cè)試! ?
... 3 / 3 (100%)...OK (3 tests, 5 assertions)Now we still need to test the creation of the recipe. To do that we can assert the recipes count of the user. Update your testCreate method as under:
現(xiàn)在,我們?nèi)匀恍枰獪y(cè)試配方的創(chuàng)建。 為此,我們可以聲明用戶的配方數(shù)。 更新您的testCreate方法,如下所示:
We can now go ahead and fill the rest of our methods. Time for some changes. First, our routes/api.php
現(xiàn)在,我們可以繼續(xù)進(jìn)行其余的方法。 是時(shí)候進(jìn)行一些更改了。 首先,我們的routes/api.php
Next, we add the methods to the controller. Update your RecipeController class this way.
接下來,我們將方法添加到控制器。 用這種方式更新RecipeController類。
The code and comments already explain the logic to a good degree.
代碼和注釋已經(jīng)在很大程度上解釋了邏輯。
Lastly our test/Feature/RecipeTest
最后我們的test/Feature/RecipeTest
Other than the additional test, the only other difference was adding a class-wide user file. That way, the authenticate method not only generates a token, but it sets the user file for subsequent operations.
除了附加測(cè)試之外,唯一的區(qū)別是添加了全班級(jí)用戶文件。 這樣, authenticate方法不僅會(huì)生成令牌,而且還會(huì)為后續(xù)操作設(shè)置用戶文件。
Now run $ vendor/bin/phpunit and you should have all green tests if done correctly.
現(xiàn)在運(yùn)行$ vendor/bin/phpunit ,如果正確完成,則應(yīng)該進(jìn)行所有綠色測(cè)試。
結(jié)論 (Conclusion)
Hopefully, this gave you an insight into how TDD works in Laravel. It is definitely a much wider concept than this, one that is not bound to a specific method.
希望這可以使您深入了解TDD在Laravel中的工作方式。 絕對(duì)比這更廣泛的概念,不限于特定方法。
Though this method of development may seem longer than the usual debug later procedure, it’s perfect for catching errors early on in your code. Though there are cases where a non-TDD approach is more useful, it’s still a solid skill and habit to get used to.
雖然這種開發(fā)方法似乎比以后的常規(guī)調(diào)試更長 過程,非常適合在代碼早期發(fā)現(xiàn)錯(cuò)誤。 盡管在某些情況下,非TDD方法更有用,但它仍然是一種扎實(shí)的技能和習(xí)慣。
The entire code for this walkthrough is available on Github here. Feel free to play around with it.
此演練的完整代碼可在此處的 Github上找到 。 隨便玩吧。
Cheers!
干杯!
翻譯自: https://www.freecodecamp.org/news/how-to-build-a-laravel-rest-api-with-test-driven-development-c4bb6417db3c/
rest laravel
總結(jié)
以上是生活随笔為你收集整理的rest laravel_如何通过测试驱动开发来构建Laravel REST API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css 计算属性的应用_如何使用一点CS
- 下一篇: 算法训练营 重编码_您在编码训练营期间可