PHPUnit - 这是正确的方法

时间:2013-09-20 10:26:08

标签: yii phpunit

我今天正在盯着PHPUnit。当我使用Yii框架时,我正在使用内置函数。

如果我正确进行,有人可以告诉我吗

这是模型函数

public function getTaxRate()
{
    if($this->province_id != 13 && $this->province_id != 14)
    {
        return 21;
    }
    elseif($this->identification[0] == 'B')
    {
        return 0;       
    }
    else
    {
        return 7;       
    }

} 

以下是测试用例

public function testgetTaxRate()
{
    $accountData = array(
                                array('identification'=>'x2', 'province_id'=>'50', 'result'=>21), // test for 21
                                array('identification'=>'x2', 'province_id'=>'13', 'result'=>7), // test for 7
                                array('identification'=>'B2', 'province_id'=>'13', 'result'=>0), // test for 0
                        );
    foreach($accountData as $account)
    {
        $acc = new Accounts();
        $acc->identification=$account['identification'];
        $acc->province_id=$account['province_id'];
        $tax = $acc->getTaxRate();
        $this->assertEquals($tax, $account['result']);
    }
}

我是否正确地执行了此操作,结果是正确的,并且在我预期时会出错。

此致

1 个答案:

答案 0 :(得分:0)

组织测试有一个很好的规则:每个案例一次测试。如果只有一个逻辑,则应使用数据提供程序机制(由PHPUnit提供)以实现此目的,以避免代码重复。

文档:http://phpunit.de/manual/3.7/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers

为您举个例子:

/**
 * @dataProvider dataProvider_getTaxRate
 */
public function testGetTaxRate($id, $provinceId, $expectedResult)
{
    $acc = new Accounts();
    $acc->identification = $id;
    $acc->province_id = $provinceId;

    $this->assertEquals($expectedResult, $acc->getTaxRate());
}

public static function dataProvider_getTaxRate()
{
    return array(
        array('x2', '50', 21),
        array('x2', '13', 7),
        array('x2', '14', 7),
        array('B2', '13', 0),
    );
}

还有一件事 - 好的习惯是期望应该是断言的第一个论点。

相关问题