【问题标题】:Injecting a validation class Instance to unit test - phpunit将验证类实例注入单元测试 - phpunit
【发布时间】: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


【解决方案1】:

只需模拟必要的方法:

$validate = $this
    ->getMockBuilder(CustomValidation::class)
    ->disableOriginalConstructor()
    ->getMock();

$validate
    ->expects($this->once())
    ->method('trimmed_no_special_characters')
    ->will($this->returnValue('some trimmed name));

您还可以制作一个方法的模拟,通过链接 in
来期望特定的输入 这个电话: ->with($this->equalTo('something'))

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多