php 8.6单元测试可以通过接口注入外部依赖,用phpunit的stub控制返回值,再用mock验证必须发生的调用。只需制造输入时使用createstub;需要检查交互次数和参数时使用createmock,避免把两者混为同一测试目的。

官方文档:What are test stubs?
隔离依赖,准备一个完整样例
安装PHPUnit并启用其要求的扩展。以下使用PHPUnit 12.5文档中的稳定测试替身API,将内容保存为tests/PriceTest.php;composer check-platform-reqs用于核对实际安装环境。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

官方文档:What are mock objects?
分别验证计算结果和通知行为
<?php
use PHPUnit\Framework\TestCase;
interface PriceSource { public function cents(): int; }
interface Notifier { public function send(int $cents): void; }
final class Quote {
public function __construct(private PriceSource $source, private Notifier $notifier) {}
public function publish(): int {
$cents = $this->source->cents();
$this->notifier->send($cents);
return $cents;
}
}
final class PriceTest extends TestCase {
public function testPublishesTheQuotedPrice(): void {
$source = $this->createStub(PriceSource::class);
$source->method('cents')->willReturn(1200);
$notifier = $this->createMock(Notifier::class);
$notifier->expects($this->once())->method('send')->with(1200);
self::assertSame(1200, (new Quote($source, $notifier))->publish());
}
}让失败清楚地指向契约
执行vendor/bin/phpunit tests/PriceTest.php。返回值错误由assertSame定位;没有通知、通知两次或参数不同由mock期望定位。接口替身不会发送通知,也不验证真实服务。不要为非契约细节设置大量调用顺序期望;final类、静态方法等也存在替身限制,通过可注入接口建立测试边界通常更清楚。


















