Home  >  Article  >  PHP Framework  >  Teach you how to master Laravel testing methods

Teach you how to master Laravel testing methods

藏色散人
藏色散人forward
2020-07-28 13:54:256233browse

The following tutorial column will introduce you to the testing method of mastering Laravel. I hope it will be helpful to friends who need it!

Master Laravel’s testing methodsTeach you how to master Laravel testing methods

Whether you admit it or not you are developing a When it comes to products, software testing is of great significance to the project, but testing is often ignored by us. In this article we mainly study the testing methods of the Laravel framework. Perhaps you don’t know yet, the Laravel kernel has already inherited the PHPUnit unit test component. PHPUnit is one of the most widely used and popular testing frameworks in the PHP community. PHPUnit supports both "unit testing" and "functional testing" features.

We will briefly introduce the basic usage of PHPUnit "unit testing" and "functional testing". Then, explain how to create "unit test" and "functional test" use cases in Laravel projects. However, in this article we assume that you already have a basic understanding of the PHPUnit testing framework, so let us focus on the topic of using PHPUnit for testing in Laravel.

Unit testing and functional testing

If you have come into contact with the PHPUnit framework, then you should know that it supports two types of features-"unit testing" and " function test". The purpose of "unit testing" is to test the correctness of functions or methods. More importantly, we can easily achieve the correctness of the code logic.

If you find that a function contains multiple logical processes during development, it is best to split each processing logic into different methods to ensure that individual methods and code blocks are testable.

We use an ideal method to peek into the mysteries of unit testing.

<?php
public function getNameAttribute($value)
{
    return ucfirst($value);
}

As you can see, this method only handles one business logic. The ucfirst function is used inside the method to convert characters into first letter capital format.

Unit testing is to ensure the correctness of the code of each independent unit; functional testing is to ensure the correctness of a function. In a nutshell, it is to simulate the behavior of users accessing the application through specific test cases to verify the correctness of the system.

For example, we can implement a functional test case for the login function that includes the following steps:

Initiate a GET request to access the login page;

  • Determine whether we are on the login page;

  • Generate login data for logging in using POST request method;

  • Determine whether the login session data is successfully created.

  • This is the secret of how to create "functional test" use cases. Next we will create specific test cases to explain how to use "unit testing" and "functional testing" in Laravel.

Build a test environment

Create a test model

Before we start creating test cases, we need to first build one for testing project dependencies. First execute the following artisan command to create a Post model and its corresponding migration file.

$ php artisan make:model Post --migration

The above command will create a Post model class and database migration file for us.

Post model code is as follows:

<?php
// app/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    //
}

The database migration file YYYY_MM_DD_HHMMSS_create_posts_table.php will be created in the database/migrations directory.

The Post data table stores the title of an article. The modified Post database migration file code is as follows:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(&#39;posts&#39;, function (Blueprint $table) {
            $table->increments(&#39;id&#39;);
            $table->string(&#39;name&#39;);
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(&#39;posts&#39;);
    }
}

As you can see, we store the title of the article through the new $table->string('name'). Next, execute the database migration command to create the corresponding data table in the database.

$ php artisan migrate

After creating the data table, we need to add the following code to the Post model class

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    /**
     * Get the post title.
     *
     * @param  string  $value
     * @return string
     */
    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }
}

We just added the accessor method, its function is to modify the title of the article, which is exactly What we want to test in the unit test case. The above is what needs to be modified in the Post model.

Create a test controller

Next, we need to create a controller with a file name app/Http/Controllers/AccessorController.php that will be used Follow-up functional testing.

<?php
// app/Http/Controllers/AccessorController.php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AccessorController extends Controller
{
    public function index(Request $request)
    {
        // get the post-id from request params
        $post_id = $request->get("id", 0);
        // load the requested post
        $post = Post::find($post_id);
        // check the name property
        return $post->name;
    }
}
In the index method, we query an article from the Post model through the id parameter in the request.

Finally, define relevant routes in the routes/web.php routing configuration file.

<?php
Route::get(&#39;accessor/index&#39;, &#39;AccessorController@index&#39;);

After setting up the route, you can access it through http://your-laravel-site.com/accessor/index to see if the route can be accessed normally.

Unit Test

In the previous section we set up an environment for testing. In this section we will write unit test cases in Laravel to test the Post model. Fortunately, Laravel also provides us with a command tool for creating test case template files.

Create the AccessorTest unit test case class by executing the following command on the command line. Note that we need to pass the --unit parameter option to indicate that this command creates a unit test case. Unit test case files are created in the tests/Unit directory.

$ php artisan make:test --unit

执行上面创建测试用例命令会创建文件名为 tests/Unit/AccessorTest.php 文件。

<?php
// tests/Unit/AccessorTest.php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AccessorTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

将 testExample 方法替换成更有实际意义的方法:

<?php
// tests/Unit/AccessorTest.php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AccessorTest extends TestCase
{
    /**
     * Test accessor method
     *
     * @return void
     */  
    public function testAccessorTest()
    {
        $db_post = DB::select(&#39;select * from posts where id = 1&#39;);
        $db_post_title = ucfirst($db_post[0]->title);
        $model_post = Post::find(1);
        $model_post_title = $model_post->title;
        $this->assertEquals($db_post_title, $model_post_title);
    }
}

我们可以看到更新后的代码和 Laravel 代码编码风格完全一致。在类的开始我们引入了相关依赖类文件。在 testAccessorTest 方法里,我们希望验证定义在 Post 模型里面的 getNameAttribute 方法的正确性。

为了实现这样的测试功能,我们通过 DB 类使用原生 SQL 查询到一篇文章,并将文章的标题赋值给 $db_post_title 变量。

之后,我们通过 Post 模型获取经过 getNameAttribute 方法处理过后的同一篇文章的标题赋值给 $model_post_title。

最后,通过 assertEquals 方法比较两个变量是否相等。

以上就是如何在 Laravel 中使用单元测试的使用方法。

功能测试

这一节我们将学习如何创建功能测试用例来对先前创建的控制器进行「功能测试」。

通过下面给出的命令,我们将创建一个名为 AccessorTest 的功能测试用例。注意这边我们没有使用 --unit 命令行选项,所以命令会在 tests/Feature 目录下创建一个「功能测试」用例。

$ php artisan make:test AccessorTest

命令会创建文件名为 tests/Feature/AccessorTest.php 的测试类。

<?php
// tests/Feature/AccessorTest.php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AccessorTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

同样我们替换掉 testExample 方法。

<?php
// tests/Feature/AccessorTest.php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AccessorTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $db_post = DB::select(&#39;select * from posts where id = 1&#39;);
        $db_post_title = ucfirst($db_post[0]->name);
        $response = $this->get(&#39;/accessor/index?id=1&#39;);
        $response->assertStatus(200);
        $response->assertSeeText($db_post_title);
    }
}

熟悉功能测试的朋友应该对上面的代码不会太陌生。

首先,我们还是通过 DB 类使用原生 SQL 查询到一篇文章,并将文章的标题赋值给 $db_post_title 变量。接着我们模拟一个访问 /accessor/index?id=1 URI 的 GET 请求,并通过 $response 变量接收响应。

然后,我们去匹配请求响应的状态码是否为 200。在我们的测试用例中的这个 GET 请求响应状态码应该是 200。此外,测试后还将获取到一个首字母大写的标题,判断标题是否与 $db_post_title 相对的方法是 assertSeeText。

编写完成所有的测试用例后。接下来需要去执行这些测试用例。在 Laravel 项目中运行 PHPUnit 测试用例,仅需在项目更目录执行下面的命令。

$ phpunit

这个命令会运行项目中的所有测试用例。测试中的断言会以标准的 PHPUnit 输出显示在控制台。

总结

今天,我们探讨了 Laravel 内置测试组件 PHPUnit 的测试用例实现方法。本文仅涉及 PHPUnit 「单元测试」和「功能测试」的基础知识,工作中我们还需要结合实际出发,对 PHPUnit 测试进行深入研究才行。

此外,我们还学习了通过使用 artisan 命令行工具创建分别创建了用于单元测试和功能测试的测试用例的方法。

原文地址:https://learnku.com/laravel/t/33394

The above is the detailed content of Teach you how to master Laravel testing methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:phpzendo. If there is any infringement, please contact admin@php.cn delete