【问题标题】:Help me write a PHPUnit Test for the following method帮我为以下方法写一个PHPUnit测试
【发布时间】:2010-05-20 15:49:28
【问题描述】:
    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() {

}

公共函数 testGetAllVideosByRfid() {

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

}

【问题讨论】:

  • 我真的不明白,你打算如何对这个程序的条目进行单元测试?这不应该是您功能中的验证吗?喜欢 - (is_string($rfid) && strlen($rfid) == 5)
  • 我编辑了我的问题以提供更多详细信息。对不起

标签: phpunit simpletest


【解决方案1】:

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

$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 中完成,因此不会为单元测试创​​建/创建真正的数据库,并且它会随着测试而生死攸关,任何地方的任何开发人员都可以使用它而无需配置。

【讨论】:

    猜你喜欢
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2018-07-04
    相关资源
    最近更新 更多