如果测试访问器是浪费时间,那么测试构造函数逻辑呢?

时间:2012-09-26 16:25:37

标签: php unit-testing testing constructor phpunit

似乎许多人认为单元测试setter和getter只是浪费时间,并且只有在包含某种逻辑时才应测试访问器。我同意。

但是那些需要一些(小的)逻辑的属性呢?

class DeliveryReportEvent extends Event
{
    private static $reasonMap = array(
        '401' => "Message expired (device off/not reachable)",
        '201' => "Operator network malfunctioning",
        '203' => "Recipient unreachable (in roaming)",
        '301' => "Invalid recipient (nonexistent/on portability/not enabled)",
        '302' => "Wrong number",
        '303' => "SMS service not enabled",
    );

    private $errorCode;

    public function __construct($errorCode)
    {
        $this->errorCode = $errorCode;

        if(array_key_exists($errorCode, self::$reasonMap)) {
            $this->errorReason = self::$reasonMap;
        }
    }

    public function getErrorCode()
    {
        return $this->errorCode;
    }

    public function getErrorReason()
    {
        return $this->errorReason;
    }
}

虽然测试getErrorCode()可能听起来很愚蠢(因为缺少逻辑和IDE功能),但测试getErrorReason()是否有意义呢?

/**
 * @dataProvider getKnownErrorCodesAndReasons
 */
public function testErrorReasonWithKnownErrorCodes($knownErrorCode,
    $expectedErrorReason)
{
    $event = $this->getMockDeliveryReportEvent($knownErrorCode);

    $actualErrorReason = $event->getErrorReason();

    $this->assertNotNull($errorReason);
    $this->assertContains($expectedErrorReason, $actualErrorReason, '', true);
}

public function getKnownErrorCodesAndReasons()
{
    return array(
        array('401', "expired"),
        array('201', "network malfunctioning"),
        array('203', "unreachable"),
        array('301', "invalid recipient"),
        array('302', "wrong number"),
        array('303', "not enabled"),
    );
}

1 个答案:

答案 0 :(得分:4)

这完全是主观的,取决于许多因素,例如:

  • 您希望测试用例具有什么级别的代码覆盖率? 一些发布管理系统定义了此覆盖范围,并且需要在发布确认之前满足其他标准。
  • getErrorReason()是一个关键功能(尽管其内部逻辑有多小)?换句话说,如果系统搞砸了会破坏系统吗?

还取决于其他因素:

  • 你有多少空闲时间?
  • 你有多少纯粹主义者?
  • 你有小胡子吗?

等等......:)