欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP單元測試?yán)?PHPUNIT深入用法(三)第2/2頁

 更新時(shí)間:2011年03月06日 21:48:19   作者:  
在本系列文章的前兩篇中PHP單元測試?yán)鳎篜HPUNIT初探和PHP單元測試?yán)鳎篜HPUNIT深入用法(二)中,分別介紹了phpunit的基本用法和phpunit中的一些重要用法。

Phpunit中的Mocking

  在介紹Mocking前,先來看下為什么要使用Mocking。舉一個(gè)數(shù)據(jù)庫查詢的例子,比如在某個(gè)應(yīng)用中,如果要測試一個(gè)數(shù)據(jù)庫的應(yīng)用,但假如這個(gè)數(shù)據(jù)庫的測試要耗費(fèi)很多資源以及編寫很復(fù)雜的單元測試的代碼的話,可以嘗試使用Mocking技術(shù)。舉例說明如下:

 

<?php
class Database
{
public function reallyLongTime()
{
$results = array(
array(1,'test','foo value')
);
sleep(100);
return $results;
}
}
?>

 

   在上面這個(gè)例子中,我們模擬了一個(gè)數(shù)據(jù)庫的操作,認(rèn)為它需要運(yùn)行很長時(shí)間。接下來我們編寫其單元測試代碼如下:

 

<?php
require_once '/path/to/Database.php';
class DatabaseTest extends PHPUnit_Framework_TestCase
{
private $db = null;
public function setUp()
{
$this->db = new Database();
}
public function tearDown()
{
unset($this->db);
}
/**
* Test that the "really long query" always returns values
*/
public function testReallyLongReturn()
{
$mock = $this->getMock('Database');
$result = array(
array(1,'foo','bar test')
);
$mock->expects($this->any())
->method('reallyLongTime')
->will($this->returnValue($result));
$return = $mock->reallyLongTime();
$this->assertGreaterThan(0,count($return));
}
}
?>

 

   注意看這段代碼中有趣的地方,這里,使用了phpunit中的getMock對象方法,這里實(shí)際上是模擬生成一個(gè)Database類的“偽實(shí)例”了,這里生成了$mock這個(gè)mock對象實(shí)例,以方便接著的單元測試中用到。接下來的這三行代碼:

 

$mock->expects($this->any())
->method('reallyLongTime')
->will($this->returnValue($result));

 

   它們的含義為:無論方法reallyLongtime執(zhí)行了多長時(shí)間,始終最后會(huì)直接返回$result這個(gè)數(shù)組的結(jié)果。這樣,你就可以通過mocking技術(shù)很輕易地去實(shí)現(xiàn)在單元測試中,繞過某些復(fù)雜的邏輯部分,而節(jié)省大量的寶貴時(shí)間提高測試效率。

  下面的這個(gè)例子,講解的是Mocking技術(shù)中的更高級用法Mockbuilder。依然以上面的例子說明:

 

<?php
public function testReallyLongRunBuilder()
{
$stub = $this->getMockBuilder('Database')
->setMethods(array(
'reallyLongTime'
))
->disableAutoload()
->disableOriginalConstructor()
->getMock();
$result = array(array(1,'foo','bar test'));
$stub->expects($this->any())
->method('reallyLongTime')
->will($this->returnValue($result));
$this->assertGreaterThan(0,count($return));
}
?>

 

   通過使用Mockbuilder,我們可以不用通過構(gòu)造函數(shù)的方法去初始化一個(gè)mock對象。這段代碼跟上一段代碼的功能其實(shí)是一樣的,只不過留意一下新的兩個(gè)方法: disableAutoload和disableOriginalConstructor,其功能分別是禁止使用php的內(nèi)置的autoload初始構(gòu)造方法和禁止調(diào)用該類原有的構(gòu)造函數(shù)。最后再看一個(gè)例子:

 

<?php
/**
* Testing enforcing the type to "array" like the "enforceTypes"
* method does via type hinting
*/
public function ttestReallyLongRunBuilderConstraint()
{
$stub = $this->getMock('Database',array('reallyLongTime'));
$stub->expects($this->any())
->method('reallyLongTime')
->with($this->isType('array'));
$arr = array('test');
$this->assertTrue($stub-> reallyLongTime ($arr));
}
?>

   在這里,我們使用了with方法,其中這個(gè)方法中指定了要傳入的參數(shù)類型為array數(shù)組類型,最后這個(gè)斷言是通過了,因?yàn)榉祷氐牡拇_是數(shù)組類型。

  更多的關(guān)于phpunit中mock的用法,請參考phpunit手冊中第11章的論述。

相關(guān)文章

最新評論