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