Tareq Albajjaly Tareq Albajjaly - 1 year ago 36
PHP Question

Injecting a validation class Instance to unit test - phpunit

I'm testing a class named City that accepts two parameters, in this class i have a name getter that return a trimmed / filtered string.

Problem

If i want to use a custom validation class, i'll have to inject it through the constructor. and i'll have to create a real object in a my test.

Question


  • Should i create a validation object and pass it to City class in my test? since i can't use a mock for this one.

  • Am i breaking the unit test isolation here?



City Class

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));
}
}


City Class after injecting a validation class

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);

}
}


Test

class CityTest extends TestCase
{
protected $city;

public function setUp()
{

$this->city = new City('Dubai', 'DXB');

}
}


Test after injecting the validation class

class CityTest extends TestCase
{

protected $city;

public function setUp()
{

$this->city = new City('Dubai', 'DXB', new CustomValidation('Dubai'));

}
}

Answer Source

Just mock the necessary method:

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

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

You can also make a method's mock, that expects a specific input by chaining in
this call: ->with($this->equalTo('something'))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download