菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
15
0

零基础学测试 1 - 在 Laravel 中使用 PHPUnit

原创
05/13 14:22
阅读数 465

创建 Laravel 应用

$ laravel new mind-geek-laravel-test-demo

进入项目

$ cd mind-geek-laravel-test-demo

运行自带的测试用例

$ vendor/bin/phpunit
OK (2 tests, 2 assertions)

可以看出,Laravel 自带了两个测试用例。总的来说,Laravel 中与测试有关的目录或文件有两个

  • 根目录下的 phpunit.xml 文件,即测试的配置文件
  • tests 目录 - 测试的主要保存目录

现在来创建第一个测试用例。

// /tests/PHPUnitTest.php
<?php
namespace Tests;

use PHPUnit\Framework\TestCase;

class PHPUnitTest extends TestCase
{
}

运行该测试用例

$ vendor/bin/phpunit tests/PHPUnitTest.php

提示类中不存在测试用例

1) Warning
No tests found in class "PHPUnitTest".

根据提示创建一个测试方法

public function testAssertions()
{
}

再次运行

$ vendor/bin/phpunit tests/PHPUnitTest.php

提示测试用例中不存在断言语句

1) PHPUnitTest::testAssertions
This test did not perform any assertions

根据提示创建一些基本的断言

public function testAssertions()
{   
    // 断言传入的条件是否为 true
    $this->assertTrue(true);
    // 断言传入的条件是否为 false
    $this->assertFalse(false);
    // 断言传入的条件是否为 null
    $this->assertNull(null); 
}

再次运行,成功通过测试

$ vendor/bin/phpunit tests/PHPUnitTest.php
OK (1 test, 3 assertions)

如果传入的值与断言不符合,就无法通过测试

public function testAssertions()
{
    $this->assertNotNull(null);
}

再次运行,则无法通过测试

$ vendor/bin/phpunit tests/PHPUnitTest.php
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

发表评论

0/200
15 点赞
0 评论
收藏
为你推荐 换一批