【发布时间】:2017-10-23 01:39:32
【问题描述】:
我正在测试一个名为 City 的类,它接受两个参数,在这个类中我有一个返回修剪/过滤字符串的名称获取器。
问题
如果我想使用自定义验证类,我必须通过构造函数注入它。我必须在我的测试中创建一个真实的对象。
问题
我应该创建一个验证对象并将其传递给我的测试中的 City 类吗?因为我不能对这个使用模拟。
我是否在这里打破了单元测试隔离?
城市类
class City
{
protected $name;
protected $shortCode;
public function __construct($name, $shortCode)
{
$this->name = $name;
$this->shortCode = $shortCode;
}
public function name()
{
return preg_replace('/[^A-Za-z]/', '', trim($this->name));
}
}
注入验证类后的城市类
class City
{
protected $name;
protected $shortCode;
protected $customValidation;
public function __construct($name, $shortCode, CustomValidation $customValidation)
{
$this->name = $name;
$this->shortCode = $shortCode;
$this->customValidation = $customValidation;
}
public function name()
{
return $this->customValidation->trimmed_no_special_characters($this->name);
}
}
测试
class CityTest extends TestCase
{
protected $city;
public function setUp()
{
$this->city = new City('Dubai', 'DXB');
}
}
注入验证类后测试
class CityTest extends TestCase
{
protected $city;
public function setUp()
{
$this->city = new City('Dubai', 'DXB', new CustomValidation('Dubai'));
}
}
【问题讨论】:
-
为什么你不能使用模拟?
-
因为 city 类中的 name getter 使用了验证方法,不知道该怎么做,或者我是否可以使用 mock
标签: php unit-testing validation oop phpunit