欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

PHPUnit 单元测试与 Mock 对象

时间:2026年08月12日 04:46:50 浏览:1

安装 PHPUnit


composer require --dev phpunit/phpunit

测试类


use PHPUnit\Framework\TestCase;

class UserTest extends TestCase
{
public function testUserFullName(): void
{
$user = new User('张三', '三' );
$this->assertEquals('张三三', $user->getFullName());
}

public function testAgeValidation(): void
{
$this->expectException(\InvalidArgumentException::class);
new User('张三', '三', -1);
}
}

数据提供器


/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertEquals($expected, $a + $b);
}

public function additionProvider(): array
{
return [
[1, 2, 3],
[0, 0, 0],
[-1, 1, 0],
];
}

Mock 对象


模拟依赖服务,隔离测试。


class OrderServiceTest extends TestCase
{
public function testCreateOrder(): void
{
$paymentMock = $this->createMock(PaymentService::class);
$paymentMock->method('charge')
->willReturn(true);

$emailMock = $this->createMock(EmailService::class);
$emailMock->expects($this->once())
->method('send')
->with($this->stringContains('订单已创建'));

$service = new OrderService($paymentMock, $emailMock);
$service->create([...]);
}
}

运行测试:./vendor/bin/phpunit


单元测试是保证代码质量的重要防线。