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

rest laravel_如何通过测试驱动开发来构建Laravel REST API相关推荐

  1. 使用 TDD 测试驱动开发来构建 Laravel REST API

    TDD 以及敏捷开发的先驱者之一的 James Grenning有句名言: 如果你没有进行测试驱动开发,那么你应该正在做开发后堵漏的事 - James Grenning 今天我们将进行一场基于 Lar ...

  2. 使用 TDD 测试驱动开发来构建 Laravel REST API 1

    TDD 以及敏捷开发的先驱者之一的 James Grenning有句名言: 如果你没有进行测试驱动开发,那么你应该正在做开发后堵漏的事 - James Grenning 今天我们将进行一场基于 Lar ...

  3. 用测试驱动开发状态机

    用测试驱动开发状态机 Developing state machines with test-driven development 由于状态机模型在嵌入式系统中的广泛应用,本文探讨了在测试驱动开发(T ...

  4. 测试驱动开发与行为驱动开发中的测试先行方法

    Gil Zilberfeld将在 Agile Practitioners会议上举办小型研讨会,讨论测试先行(test first)方法,测试驱动开发(TDD)和行为驱动开发(BDD)的基础. \\ \ ...

  5. 测试驱动开发 测试前移_测试驱动开发简介

    测试驱动开发 测试前移 I've been programming for five years and, honestly, I have avoided test-driven developme ...

  6. 测试驱动开发 测试前移_测试驱动的开发可能看起来是工作的两倍-但无论如何您都应该这样做...

    测试驱动开发 测试前移 by Navdeep Singh 通过Navdeep Singh 测试驱动的开发可能看起来是工作的两倍-但无论如何您都应该这样做 (Test-driven developmen ...

  7. 测试驱动开发是否是一种强迫症?

    \ 本文要点 \\ 现代软件测试中,开发人员需编写测试,并逐渐负责测试自己及同事的代码.\\t 害怕失败或"评价焦虑"是十分常见的心理状态,它们受自我测试和团队测试的直接影响.\\ ...

  8. tdd测试驱动开发课程介绍_测试驱动开发的实用介绍

    tdd测试驱动开发课程介绍 by Luca Piccinelli 通过卢卡·皮奇内利 测试驱动开发很难! 这是不为人知的事实. (Test Driven Development is hard! Th ...

  9. 测试驱动开发 测试前移_我如何以及为什么认为测试驱动开发值得我花时间

    测试驱动开发 测试前移 by Ronauli Silva 通过罗纳利·席尔瓦(Ronauli Silva) I first read about test driven development (TD ...

最新文章

  1. PCL中点云数据格式之间的转化
  2. android studio 各种问题
  3. JS,JQ,PHP的小知识点整理
  4. 把剪贴板里面的数据放到内表
  5. FCN网络训练 SIFTFLOW数据集
  6. KVM虚拟化实战精讲[第五章 利用virsh对虚拟机管理]
  7. 隐藏的东西? 您需要HiddenSidesPane
  8. 奶牛健美操(codevs 3279)
  9. 13建造者模式(Builder)
  10. 关于设置table样式后,不停点击按钮table中的数据会逐渐被最后一行替换的问题...
  11. 需求规格说明书5.0版本
  12. 密码编码学与网络安全(第五版)答案
  13. 迷你世界怎么显示服务器未连接,打开迷你世界提示网络异常或者连接不上
  14. 腾讯是如何一刀刀,在15年间干死那些竞争对手的?! (zz)
  15. python中单引号的作用_python里的单引号和双引号的有什么作用
  16. 可以查看计算机主要自启动项的技术,电脑中怎么查看启动项
  17. JAVA基础-GUI实践总结
  18. matlab的积分函数
  19. 【bug】vue.runtime.esm.js?2b0e:619 [Vue warn]: Failed to mount component: template or render function
  20. ubuntu未关机断电导致异常进入initramfs界面的处理方法

热门文章

  1. 期权价格的上限和下限
  2. anaconda在win下和在mac下的安装区别
  3. Android近场通信---NFC基础(二)(转)
  4. spring容器扩展功能之一:spring加载ApplicationContext.xml的四种方式
  5. fastjson反序列化漏洞原理及利用
  6. UNITY3D 脑袋顶血顶名
  7. Apache+Tomcat集群负载均衡的两种session处理方式
  8. 开发工具总结(2)之全面总结Android Studio2.X的填坑指南
  9. ? SegmentFault Hackathon 文艺复兴上海站作品集 - 获奖篇
  10. Mac下关于-您不能拷贝项目“”,因为它的名称太长或包括的字符在目的宗卷上无效。-的删除...