0

似乎很多人认为单元测试 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"),
    );
}
4

1 回答 1

4

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

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

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

  • 你有多少空闲时间?
  • 你是一个多么纯粹的人?
  • 你有胡子吗?

等等等等.. :)

于 2012-09-26T16:32:18.197 回答