7.创建便于测试的辅助函数

未匹配的标注

本节说明#

  • 对应视频第 7 小节:Let's Make Some Testing Helpers

本节内容#

本节让我们来建立一些测试时用到的辅助函数,方便我们进行编写测试:
修改 composer.json

.
.
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    },
    "files":["tests/utilities/functions.php"]  -->这里增加一行
},
.
.

新建 tests/utilities/functions.php 文件,执行命令将该文件加载进来:

$ composer dump-autoload

我们将获取模型实例这样的方法,例如 create()make() 抽离出来,放到 functions.php 中:
\tests\utilities\functions.php

<?php

function create($class,$attributes = [])
{
    return factory($class)->create($attributes);
}

function make($class,$attributes = [])
{
    return factory($class)->make($attributes);
}

function raw($class,$attributes = [])
{
    return factory($class)->raw($attributes);
}

在很多测试中,我们需要测试用户是否登录。在之前的测试当中,我们使用了 be()actingAs() 方法来得到一个已登录用户。现在我们在 TestCase.php 新建 signIn() 方法,将用户登录的逻辑放在基类文件中:
\tests\TestCase.php

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function signIn($user = null)
    {
        $user = $user ?: create('App\User');

        $this->actingAs($user);

        return $this;
    }
}

现在我们需要重构之前的代码,将像 factory('App\Reply')->create() 这样的代码片段更改为 create('App\Reply')be()actingAs() 方法更改为 signIn() 方法。
对于使用 PHP Storm 的 开发人员,我们有建立测试更加便捷的方法:

  1. 新建一个 template:
    file
  2. 在相对应的位置填充完模板,在点击 Edit variables
    file
  3. 定义应用的位置 everywhere
    file
  4. 勾上 Reformat according to style
    file
  5. 最后点击 Apply 应用设置,再点击 OK
    file
    建完模板之后,再新建一个 PHP 文件,输入 testclass 后使用 Tab 键即可补齐模板,十分便捷。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~