doucaishi0077 2012-02-20 02:45
浏览 30
已采纳

如何在PHPUnit中实现If / Else的代码覆盖率?

Disclaimer: I'm new to unit testing and just getting my feet wet. That being said, I understand 100% is not always possible, but I'm curious if there is a solution to code coverage with if/else statements such as this or if they are just untestable.

The function:

public function getAll() 
{

    // Query table for all rows sorted by name
    $select = $this->select();
    $select->order('name ASC');
    $rowset = $this->fetchAll($select);

    // Validate and return row
    if($rowset->current())
    {   
        // Return rowset
        return $rowset;
    }
    else { return false; }

}

The Unit Test

public function testCanGetAll()
{
    // Try to get all states
    $result = $this->model->getAll();
    $this->assertNotNull($result);
    $this->assertNotEquals(false,$result);
}

The Result

enter image description here

As you can see, I can't cover the return false; line. The only way I can think of to test it is to rename my database table or something drastic like that.

Is there another way to write functions with if/else statements (which are a fairly common practice) which allows for easier code coverage?

[EDIT] Perhaps it's better to not check results in the function, and just return it? Whatever calls this function has to do it's own checking?

public function getAll() 
{

    // Query table for all rows sorted by name
    $select = $this->select();
    $select->order('name ASC');
    $rowset = $this->fetchAll($select);

    // Return rowset whether valid or not
    return $rowset; 

}
  • 写回答

1条回答 默认 最新

  • dsgw3315 2012-02-20 02:48
    关注

    Create a db context where the result would return no rows, then in your second test method create a row in that db context.

    Its usually not a good idea to test against your actual application's DB

    you should be cloning it for your tests so that you can manipulate the data to test how the application will respond to varying data contexts.

    --EDIT----

    Following this guide may help: http://framework.zend.com/manual/ru/zend.test.phpunit.db.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里