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



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

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

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"),
    );
}

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

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

还取决于其他因素,例如:

  • 你有多少空闲时间?
  • 你有多纯粹?
  • 你有胡子吗?
等等

等等。 :)

最新更新