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.

注意:本演练假定您了解LaravelPHPUnit的基本概念。 如果您不打算这么做? 开车吧

设置项目 (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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值