PHPUnit#2 โครงสร้างการใช้งาน phpunit by joeskb
Dec0
เริ่มการเขียน PHPUnit Test case
ด้วยการเรียกใช้ไฟล์ bootstrap.php ที่ได้ทำการตั้งค่าต่างๆ เอาไว้
โดยทำการ include_once เข้ามาใน file ที่กำลังจะเขียน
function หลักที่นอกเหนือจาก Test case ของเราเองก็จะมี
- setUpBeforeClass จะถูกเรียกใช้งานก่อนจะเริ่ม class
- setUp จะถูกเรียกใช้งานก่อนจะเริ่ม function test
- tearDown จะถูกเรียกใช้งานหลังจากจบ function test
- tearDownAfterClass จะถูกเรียกใช้งานหลังจากจบ class
ประกาศ function setUpBeforeClass และ tearDownBeforeClass โดย
public static function setUpBeforeClass
public static function tearDownBeforeClass
ส่วน setUp และ tearDown ใช้การประกาศ function ตามปกติ
ส่วนเสริมที่แนะนำก็จะมีการ testException กับ dataProvider
เริ่มจาก dataProvider นะครับ เป็น function ที่จะ return array(array()) มาให้ function เป็นชุดๆ
โดย function ที่ต้องการจะใช้งาน dataProvider จะต้องการใส่ comment ไว้บนหัว function
ว่า dataProvider ตามด้วย
/**
* @dataProvider
*/
ด้านล่างนี้เป็นตัวอย่าง testException จาก dataProvider ทำให้เราไม่ต้องไป try ทีละตัวแปรภายใน function test
function exceptionUserIdProvider() {
return array(
array(NULL, 'user id cannot be null'),
array('a', 'user id must be numberic'),
array(1.11, 'user id must not be float'),
array('1.11', 'user id must not be float'),
array(-1, 'user id must not less than zero'),
array(array(1), 'user id must not be array'),
);
}
/**
* @dataProvider exceptionUserIdProvider
*/
function testFunctionException($id, $message) {
$this->setExpectedException('Exception', $message);
$this->test->function($id);
}
Enjoy this article?
Consider subscribing to our RSS feed!
ไม่มีความเห็น
ยังไม่มีความเห็น