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

创建 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.
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!