零基础学测试 2 - 进一步理解 Laravel 的测试与 PHP Unit 的关系
细心的读者可以发现,上一讲中创建的用例继承的是 PHPUnit 的测试基类。
<?php
namespace Tests;
use PHPUnit\Framework\TestCase;
class PHPUnitTest extends TestCase
{
public function testAssertions()
{
$this->assertTrue(true);
$this->assertFalse(false);
$this->assertNull(null);
}
}
而 Laravel 的测试用例则是继承自 tests
目录下的 TestCase
基类,该基类只是在 PHPUnit 的 TestCase
类的基础上增加了一些功能(HTTP 测试、命令行测试、数据库测试等)。
例如,自带的 ExampleTest
测试使用了 Laravel 提供的 HTTP 测试功能
// /tests/Feature/ExampleTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
// /vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
$response = $this->get('/');
// /vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php
$response->assertStatus(200);
}
}
通过修改路由文件来让测试用例无法通过
// /routes/web.php
Route::get('/', function () {
abort(404);
});
运行测试
$ vendor/bin/phpunit tests/Feature/ExampleTest.php
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
本作品采用《CC 协议》,转载必须注明作者和本文链接