PHP Unit Testing (PHPUnit)
In this page:
use PHPUnit\Framework\TestCase;
class ClassNameTest extends TestCase {
public function testSomething() {
$this->assertEquals(expected, actual);
}
}
Unit Testing का Introduction
Unit testing code के छोटे, isolated pieces -- आमतौर पर एक single function या method -- को automated fashion में check करता है, किसी change के कुछ तोड़ते ही regressions पकड़ते हुए बजाय हफ्तों बाद manual QA के दौरान।
उदाहरण: Introduction to Unit Testing
<?php
function add($a, $b) {
return $a + $b;
}
// A unit test would automatically check: add(2, 3) === 5
var_dump(add(2, 3) === 5);
?>
Login to try C/C++/Java/PHP code in the editor
अपना पहला Test लिखना
एक PHPUnit test class TestCase को extend करती है और methods define करती है (conventionally test से prefixed) जो हर एक एक specific behavior exercise करते हैं और assert करते हैं कि correct outcome क्या होना चाहिए।
उदाहरण: Writing your First Test
<?php
// use PHPUnit\Framework\TestCase;
// class MathTest extends TestCase {
// public function testAddition() {
// $this->assertEquals(5, add(2, 3));
// }
// }
echo "A PHPUnit test class extends TestCase";
?>
Login to try C/C++/Java/PHP code in the editor
Test Assertions
PHPUnit दर्जनों purpose-built assertions के साथ आता है -- assertEquals, assertArrayHasKey, assertStringContainsString -- जो एक bare if-check से कहीं ज़्यादा informative failure messages produce करते हैं।
उदाहरण: Test Assertions
<?php
// $this->assertEquals(5, add(2, 3));
// $this->assertArrayHasKey('id', $user);
// $this->assertStringContainsString('Alice', $greeting);
echo "PHPUnit assertions produce clear failure messages";
?>
Login to try C/C++/Java/PHP code in the editor
Testing Setup और Teardown
setUp() हर single test method से पहले fresh fixtures तैयार करने के लिए चलता है (जैसे एक clean database connection), और tearDown() हर एक के बाद साफ करने के लिए चलता है, tests को एक-दूसरे से पूरी तरह isolated रखते हुए।
उदाहरण: Testing Setup and Teardown
<?php
// protected function setUp(): void { $this->db = new SQLite3(':memory:'); }
// protected function tearDown(): void { $this->db->close(); }
echo "setUp runs before, tearDown runs after each test method";
?>
Login to try C/C++/Java/PHP code in the editor
PHPUnit चलाना
terminal से phpunit चलाना *Test.php से match करने वाली files के लिए आपकी test directory scan करता है और मिले हर test method execute करता है, एक ही command में पूरे suite के लिए एक pass/fail summary report करते हुए।
उदाहरण: Running PHPUnit
<?php
// Run in terminal: phpunit
echo "Scans for *Test.php files and reports a pass/fail summary";
?>
Login to try C/C++/Java/PHP code in the editor
- एक test method में कई behaviors test करना, ताकि एक failure यह न दिखाए कि कौन सा टूटा।
- tests के order पर depend करना, जबकि हर test को अपनी state खुद setup करनी चाहिए।
- test methods को
testprefix या@testannotation से नाम देना भूल जाना, ताकि PHPUnit उन्हें न चलाए।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: