开发者

Help me write a PHPUnit Test for the following method

    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 开发者_StackOverflowrfid has been claimed

return 0;

}

My assertions are : 1). $rfid is a string 5 characters long 2). I am getting a valid result set

Thank You

Please assume that I have the following Unit Test code:

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() {

******What should I put here*****

}


You need to decentralize your database, typically with a Database abstraction layer which you would mock out. Thus adding a ->setDatabase(), etc. on the object that has the method you are using. Then inside your setUp() { ... } you would set the Database object to a mock:

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

Then you would change

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

to use some form of PDO - so that you could call setDatabase() with a PDO Sql Lite. For example:

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.
   }
}

Typically this would all be done in PDO Sqlite so that no true database would be made/created just for the unit test & that it would live and die with the test, and any developer anywhere could use it with no configuration needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜