在Linux中,对Laravel进行单元测试主要遵循以下步骤:
composer require --dev phpunit/phpunit
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
verbose="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Laravel Application Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix="Model.php">./app</directory>
</whitelist>
</filter>
</phpunit>
这个配置文件指定了测试文件的目录(./tests),并设置了自动加载依赖。同时,它还配置了一个过滤器,用于指定哪些文件应该被测试。
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
// ...
}
<?php
namespace Tests;
use Tests\TestCase;
use App\Models\User;
class ExampleTest extends TestCase
{
/** @test */
public function it_can_add_two_numbers()
{
$result = 1 + 1;
$this->assertEquals(2, $result);
}
/** @test */
public function it_creates_a_new_user()
{
$user = User::factory()->create();
$this->assertInstanceOf(User::class, $user);
$this->assertNotNull($user->id);
}
}
vendor/bin/phpunit
PHPUnit将自动发现并运行tests目录下的所有测试类和方法。测试结果将显示在终端中,包括通过的测试、失败的测试以及失败的原因。
vendor/bin/phpunit --coverage-html reports
这将在项目根目录下生成一个名为reports的目录,其中包含代码覆盖率报告。可以使用浏览器打开reports/index.html文件查看报告。
通过以上步骤,可以在Linux环境下对Laravel项目进行单元测试。在实际项目中,可能需要根据项目的具体情况调整配置和测试方法。