我正在测试一个名为City的类,它接受两个参数,在这个类中我有一个名称getter,它返回一个修剪/过滤的字符串。
问题
如果我想使用自定义验证类,我将不得不通过构造函数注入它。我将不得不在我的测试中创建一个真实的对象。
问题
我应该在测试中创建验证对象并将其传递给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'));
}
}
答案 0 :(得分:0)
嘲笑必要的方法:
$validate = $this
->getMockBuilder(CustomValidation::class)
->disableOriginalConstructor()
->getMock();
$validate
->expects($this->once())
->method('trimmed_no_special_characters')
->will($this->returnValue('some trimmed name));
你也可以制作一个方法模拟,通过链接来预期特定输入
这个电话:
->with($this->equalTo('something'))