Does this PHPUnit test make sense (or am I testing a framework / PHP)?

I am just starting with PHPUnit and TDD.

In particular, I cannot answer this question: is this a good test? Am I really testing my code or something already tested (i.e. the Framework or PHP itself)?

A small example: this is a tag:

class DateMax extends Constraint { /** * @var string */ public $limit; /** * @var string */ private $invalidLimit = 'Option "limit" should be a valid date/time string.'; public function __construct($options = null) { parent::__construct($options); if(false === strtotime($this->limit)) { throw new InvalidOptionsException($this->invalidLimit, ['limit']); } } } 

I want to check that an InvalidOptionsException is expected when invalid "limit" options are passed, otherwise $constraint->limit contains the correct value:

 /** * @dataProvider getInvalidLimits * @expectedException InvalidOptionsException */ public function testInvalidLimits($testLimit) { new DateMax($testLimit); } /** * @dataProvider getValidLimits */ public function testValidLimits($testLimit) { $constraint = new DateMax($testLimit); $this->assertEquals($testLimit, $constraint->limit); } /** * @return array[] */ public function getInvalidLimits() { return array(array('invalid specification'), array('tomorr')); } /** * @return array[] */ public function getValidLimits() { return array(array('now'), array('+1 day'),array('last Monday')); } 

So the question is , does this make sense or am I testing the frame / PHP myself?

+4
source share
1 answer

Of course, this makes sense because you are redefining the constructor of the Constraint class, and there is a chance that you will break something inside it. Therefore, based on the logic of the constructor, you basically want to check two things:

  • check if you call the parent constructor with the same parameters exactly once (you can use mock for this purpose, you do not need to set the corresponding limit value, because this should be checked in the Constraint class)
  • check if an appropriate exception was thrown if the constraint has the wrong value (e.g. null)

edit: In some cases, using the first test may be useful:

Say at some point you want to extend the DateMax constructor as follows:

 public function __construct($options = null) { $this->optionsWithDecrementedValues = $this->doWeirdThings($options); parent::__construct($options); if(false === strtotime($this->limit)) { throw new InvalidOptionsException($this->invalidLimit, ['limit']); } } 

but, for example, you have not noticed that the doWeirdThings method takes a link as an argument. Thus, it actually changes the value of $ options, which you did not expect, but the first test fails, so you will not miss it.

+2
source

Source: https://habr.com/ru/post/1435452/


All Articles