简体   繁体   English

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

[英]How to Achieve Code Coverage for If/Else in PHPUnit?

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 . 话虽这么说,我理解并非总是有100%的可能性,但是我很好奇是否存在使用if / else这样的代码覆盖代码的解决方案,或者它们只是不可测试的

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 结果

在此处输入图片说明

As you can see, I can't cover the return false; 如您所见,我无法覆盖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? 还有另一种使用if / else语句编写函数的方法(这是一种相当普遍的做法),它可以简化代码覆盖范围吗?

[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; 

}

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 遵循本指南可能会有所帮助: http : //framework.zend.com/manual/ru/zend.test.phpunit.db.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM