帮我写一个PHPUnit测试,用于以下方法

时间:2010-05-20 15:49:29

标签: phpunit simpletest

    public function getAvailableVideosByRfid($rfid, $count=200) {

$query="SELECT id FROM sometable WHERE rfid='$rfid'";
$result = mysql_query($query);
$count2 = mysql_num_rows($result);

if ($count2){ //this rfid has been claimed

return 0;

}

我的断言是: 1)。 $ rfid是一个长度为5个字符的字符串 2)。我得到了一个有效的结果集

谢谢

请假设我有以下单元测试代码:

class videoSharingTest extends PHPUnit_Framework_TestCase {

/**
 * @var videoSharing
 */
protected $object;

/**
 * Sets up the fixture, for example, opens a network connection.
 * This method is called before a test is executed.
 */
protected function setUp() {
    $this->object = new videoSharing;
}

/**
 * Tears down the fixture, for example, closes a network connection.
 * This method is called after a test is executed.
 */
protected function tearDown() {

}

public function testGetAllVideosByRfid(){

******我应该把这里放什么*****

}

1 个答案:

答案 0 :(得分:1)

您需要分散数据库,通常使用您要模拟的数据库抽象层。因此,在具有您正在使用的方法的对象上添加 - > gt。setDatabase()等。然后在setUp(){...}中,你将Database对象设置为mock:

$this->object->setDatabase($mockDb);

然后你会改变

$ result = mysql_query($ query); $ count2 = mysql_num_rows($ result);

使用某种形式的PDO - 以便您可以使用PDO Sql Lite调用setDatabase()。例如:

setUp() { $this->object->setDatabase($mockDb); }
testFunction() {
   $rfid = 'the rfid to use in the test';

   //make sure no videos exist yet
   $this->assertEquals(0, count($this->object->getAvailableVideosByRfid($rfid, ..);

   //you may want to assert that it returns a null/false/empty array/etc.

   $db = $this->object->getDatabase();
   $records = array(... some data ...);
   $db->insert($records); //psuedo code
   $vids = $this->object->getAvailableVideosByRfid($rfid, ..); //however you map
   $this->assertEquals(count($records), count(vids));

   foreach($vids as $video) {
      //here you would map the $video to the corresponidng $record to make sure all 
        vital data was stored and retrieved from the method.
   }
}

通常,这将全部在PDO Sqlite中完成,因此不会为单元测试而创建/创建真正的数据库。它会在测试中生存和死亡,任何地方的开发人员都可以在没有配置的情况下使用它。