Capture and verify function output with expectOutputString() and expectOutputRegex().
Testing Output
class OutputTest extends TestCase {
public function testPrintsHello(): void {
$this->expectOutputString("Hello, World!");
(new Greeter)->greet("World");
}
public function testOutputContains(): void {
$this->expectOutputRegex("/Hello, w+!/");
(new Greeter)->greet("Alice");
}
// Capture output manually
public function testCaptureOutput(): void {
ob_start();
(new Greeter)->greet("Bob");
$output = ob_get_clean();
$this->assertStringContainsString("Bob", $output);
}
// Test JSON output
public function testJsonResponse(): void {
ob_start();
(new ApiController)->users();
$raw = ob_get_clean();
$data = json_decode($raw, true);
$this->assertArrayHasKey("data", $data);
$this->assertEquals(200, $data["status"]);
}
}