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 Grenning

Today 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/Unittests/Feature文件夹中都删除ExampleTest ,以免干扰我们的测试结果,我们一切顺利。

编写代码 (Writing the code)

  1. 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.

这一步很简单,我们要做的就是向我们的控制器添加authenticateregister方法。 在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:49
FAILURES!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:

查看日志文件,我们可以发现罪魁祸首是RecipeUser类中的publisherrecipes关系。 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392606.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python之numpy

numpy是一个多维的数组对象,类似python的列表,但是数组对象的每个元素之间由空格隔开。 一、数组的创建 1.通过numpy的array(参数),参数可以是列表、元组、数组、生成器等 由arr2和arr3看出,对于多维数组来说,如果最里…

git 上传

转载于:https://www.cnblogs.com/benbentu/p/6543154.html

Liferay 部署war包时候的deployDirectory 细节分析

引入: 在上文中,我们从宏观上讲解了Liferay部署war包的动作是如何触发监听器并且完成部署过程的,但是其中最核心的一块deployDirectory我们没讲,它的作用是当有了临时目录并且已经把war包的内容展开到该目录之后,是如何…

leetcode 164. 最大间距(桶排序)

给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 如果数组元素个数小于 2,则返回 0。 示例 1: 输入: [3,6,9,1] 输出: 3 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。 示例 2: …

批处理定时mysql备份数据库_定时备份mysql数据库的批处理

定时备份mysql数据库的批处理代码,保存为backup_mysql.bat,运行即可。复制代码 代码如下:echo offset txt1%date:~0,4%::当前年set txt2%date:~5,2%::当前月set txt3%date:~8,2%::当前日set txt4%time:~0,2%::当前小时set txt5%time:~3,2%::当前分钟set …

算法训练营 重编码_您在编码训练营期间可能面临的最大挑战

算法训练营 重编码by Joanna Gaudyn乔安娜高登(Joanna Gaudyn) 您在编码训练营期间可能面临的最大挑战 (The biggest struggles you might face during a coding bootcamp) You think that during a coding bootcamp nothing can be more challenging than learning programmi…

1449 砝码称重(思维)

题目链接:https://www.51nod.com/onlineJudge/submitDetail.html#!judgeId259281 题解:这题有一个技巧,毕竟是w^0,w^1,w^2....这样,必然会想到w进制,而且就只能用一次。 那么就简单了,把m拆成w进制&#xf…

leetcode 454. 四数相加 II(哈希表)

给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] B[j] C[k] D[l] 0。 为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间&#xf…

“换标”Intel的穷则思变

成语有云“穷则思变”,用这个词来形容早先的Intel换标也最恰当不过。当然这里“穷”,不是说Intel很贫穷,而是说Intel在自己的产业到了尽头。Intel推产品概念的水平是一流的,虽然某些概念事后被认为是错误的(如&#xf…

mysql开发中遇到的坑_mysql优化过程中遇见的坑(mysql优化问题特别注意)

单条查询最后添加 LIMIT 1,停止全表扫描。对于char(4) 或者vachar(4),无论是中文还是英文都是存储四个字符,注意是字符而不是字节。如果一个字段未int类型,此类型只有0、1两个状态,需要为此建立索引吗?过度…

初级开发人员的缺点_在您作为初级开发人员的第一年获得此建议

初级开发人员的缺点Are you a junior developer embarking on your software development career?您是从事软件开发事业的初级开发人员吗? Or a recent computer science graduate who has recently started a new job?还是最近刚开始从事新工作的计算机科学专业…

Spark日志分析

根据tomcat日志计算url访问了情况,具体的url如下, 要求:区别统计GET和POST URL访问量 结果为:访问方式、URL、访问量 输入文件: 196.168.2.1 - - [03/Jul/2014:23:36:38 0800] "GET /course/detail/3.htm HTTP/1.…

进程、线程和协程的区别

首先,给出“进程、线程和协程”的特点: 进程:拥有自己独立的堆和栈,既不共享堆,也不共享栈,进程由操作系统调度;线程:拥有自己独立的栈和共享的堆,共享堆,不共…

leetcode 493. 翻转对(分治算法)

给定一个数组 nums &#xff0c;如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对。 你需要返回给定数组中的重要翻转对的数量。 示例 1: 输入: [1,3,2,3,1] 输出: 2 代码 class Solution {public int reversePairs(int[] nums) {return getR…

使用brew安装软件

brew 又叫Homebrew&#xff0c;是Mac OSX上的软件包管理工具&#xff0c;能在Mac中方便的安装软件或者卸载软件&#xff0c; 只需要一个命令&#xff0c; 非常方便 brew类似ubuntu系统下的apt-get的功能 阅读目录 安装brew 使用brew安装软件 使用brew卸载软件 使用brew查询软…

mysql 绕过select报错_MySQL注射绕过技巧(三)

在测试一次注入的时候发现过滤了逗号 所以找到这个思路第一次遇到的时候是看key哥挖洞 遇到后就想记录下来正文过滤了逗号 利用join来逐步查询select*from(select 1)a join (select 2)b join (select 3)c;例如下图逐步查询user()user() basediruser() basedir version()也可以…

深入理解javascript

深入理解JavaScript系列&#xff08;1&#xff09;&#xff1a;编写高质量JavaScript代码的基本要点 深入理解JavaScript系列&#xff08;2&#xff09;&#xff1a;揭秘命名函数表达式 深入理解JavaScript系列&#xff08;3&#xff09;&#xff1a;全面解析Module模式 深入理…

spark 并行处理_如何使用Spark集群并行处理大数据

spark 并行处理by Hari Santanam通过Hari Santanam 如何使用Spark集群并行处理大数据 (How to use Spark clusters for parallel processing Big Data) 将Apache Spark的弹性分布式数据集(RDD)与Databricks一起使用 (Use Apache Spark’s Resilient Distributed Dataset (RDD)…

django前后端分离部署

部署静态文件&#xff1a; 静态文件有两种方式1&#xff1a;通过django路由访问2&#xff1a;通过nginx直接访问 方式1&#xff1a; 需要在根目录的URL文件中增加&#xff0c;作为入口 url(r^$, TemplateView.as_view(template_name"index.html")), 在setting中更改静…

Citrix、Microsoft、VMware虚拟桌面之网页接口登录对比

软件环境 Citrix Xendesktop 5.6 Microsoft Windows Server 2008 R2 Hyper-v VMware View client 4.6 首先看citrix的&#xff0c;很早之前Citrix就推出了网页的虚拟桌面和应用程序&#xff0c;默认是单点登录获取桌面 下面是微软的&#xff0c;和citrix很类似&#xff0c; 据我…