rest laravel_如何通过测试驱动开发来构建Laravel REST API
rest laravel
by Kofo Okesola
由Kofo Okesola
如何通過測試驅動開發來構建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和敏捷開發方法學的先驅之一James Grenning引用了著名的話:
If you’re not doing test-driven development, you’re doing debug-later development - James Grenning如果您不進行測試驅動的開發,那么就在進行后期調試-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. ?
今天,我們將進行由測試驅動的Laravel之旅。 我們將創建具有身份驗證和CRUD功能的Laravel REST API,而無需打開Postman或瀏覽器。 ?
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的基本概念。 如果您不打算這么做? 開車吧
設置項目 (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創建一個新的Laravel項目。
Next, we need to run the authentication scaffolder that we would use, go ahead and run php artisan make:auth then php artisan migrate.
接下來,我們需要運行將使用的身份驗證支架,繼續運行php artisan make:auth然后運行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.
我們實際上不會使用生成的路線和視圖。 對于此項目,我們將使用jwt-auth 。 所以,盡管設置它在你的應用程序。
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命令上遇到錯誤,則可以遵循此修補程序,直到將其添加到穩定版本中為止。
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 ,以免干擾我們的測試結果,我們一切順利。
編寫代碼 (Writing the code)
Begin by setting your auth configuration to use the JWT driver as default:
首先將您的auth配置設置為默認使用JWT驅動程序:
Then add the following to your routes/api.php file:
然后將以下內容添加到您的routes/api.php文件中:
2. Now that we have our driver set up, set up your user model in the same way:
2.現在我們已經設置了驅動程序,以相同的方式設置您的用戶模型:
What we did was that we just implemented the JWTSubject and added the required methods.
我們所做的是,我們剛剛實現了JWTSubject并添加了所需的方法。
3. Next, we need to add our authentication methods in the controller.
3.接下來,我們需要在控制器中添加身份驗證方法。
Run php artisan make:controller AuthController and add the following methods:
運行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方法中,我們驗證輸入,嘗試登錄,如果成功,則返回令牌。 在register方法中,我們驗證輸入,使用輸入創建新用戶,并基于該輸入為用戶生成令牌。
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.接下來,進入好部分。 測試我們剛剛寫的內容。 使用php artisan make:test AuthTest生成測試類。 在新的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.
上面代碼中的注釋幾乎描述了該代碼。 您應該注意的一件事是,我們如何在每次測試中創建和刪除用戶。 測試的全部重點是它們應該彼此獨立,并且理想情況下數據庫狀態應獨立。
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.
現在運行$vendor/bin/phpunit或$ phpunit如果已全局安裝)。 運行該命令將給您成功的斷言。 如果不是這種情況,您可以瀏覽日志,修復并重新測試。 這是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.現在我們可以進行身份??驗證了,讓我們為CRUD添加項目。 在本教程中,我們將使用食物食譜作為CRUD項目,因為為什么不呢?
Start by creating our migration php artisan make:migration create_recipes_table and add the following:
首先創建我們的遷移php artisan make:migration create_recipes_table并添加以下內容:
Then run the migration. Now add the model using php artisan make:model Recipe and add this to our model.
然后運行遷移。 現在,使用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.現在我們需要用于管理配方的端點。 首先,我們將創建控制器php artisan make:controller RecipeController 。 接下來,編輯routes/api.php文件并添加create端點。
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生成功能測試, php artisan make:test RecipeTest編輯內容:
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.
該代碼是不言自明的。 我們要做的就是創建一個處理用戶注冊和令牌生成的方法,然后在testCreate()方法中使用該令牌。 請注意,使用了RefreshDatabase特性,該特性是Laravel在每次測試后重置數據庫的便捷方法,這對于我們漂亮的小項目是完美的。
OK, so for now, all we want to assert is the status of the response, go ahead and run $ vendor/bin/phpunit.
好的,現在,我們要斷言的只是響應的狀態,繼續運行$ vendor/bin/phpunit 。
If all goes well, you should receive an error. ?
如果一切順利,您應該會收到一個錯誤消息。 ?
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:
查看日志文件,我們可以發現罪魁禍首是Recipe和User類中的publisher和recipes關系。 Laravel嘗試在表中查找user_id列并將其用作外鍵,但是在我們的遷移中,我們將publisher_id設置為外鍵。 現在,根據以下內容調整行:
//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! ?
然后重新運行測試。 如果一切順利,我們將獲得所有綠色測試! ?
... 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:
現在,我們仍然需要測試配方的創建。 為此,我們可以聲明用戶的配方數。 更新您的testCreate方法,如下所示:
We can now go ahead and fill the rest of our methods. Time for some changes. First, our routes/api.php
現在,我們可以繼續進行其余的方法。 是時候進行一些更改了。 首先,我們的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.
代碼和注釋已經在很大程度上解釋了邏輯。
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.
除了附加測試之外,唯一的區別是添加了全班級用戶文件。 這樣, authenticate方法不僅會生成令牌,而且還會為后續操作設置用戶文件。
Now run $ vendor/bin/phpunit and you should have all green tests if done correctly.
現在運行$ vendor/bin/phpunit ,如果正確完成,則應該進行所有綠色測試。
結論 (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中的工作方式。 絕對比這更廣泛的概念,不限于特定方法。
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.
雖然這種開發方法似乎比以后的常規調試更長 過程,非常適合在代碼早期發現錯誤。 盡管在某些情況下,非TDD方法更有用,但它仍然是一種扎實的技能和習慣。
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
總結
以上是生活随笔為你收集整理的rest laravel_如何通过测试驱动开发来构建Laravel REST API的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css 计算属性的应用_如何使用一点CS
- 下一篇: 算法训练营 重编码_您在编码训练营期间可