0

I had little dispute with my coworkers about unit testing simple class. I have to test simple class like that.

class Person
{
  /** @var string */
  protected $name

  public function __construct(string $name)
  {
    $this->name = $name;
  }

  public function __toString(): string
  {
    return (string) $this->name;
  }
}

We both agree on testing toString method. But in my opinion, first we have to test creating this object as such:

public function testObjectCreation()
{
  $testSubject = new Person('name');

  $this->assertInstanceOf(Person::class, $testSubject);
}

My question is: Is there any sense in testing this case?

  • 5
    I doubt that you need this test. – u_mulder Jan 25 '19 at 14:57
  • 2
    In this literal example, or in general? There's no point in testing that PHP's `__construct` works, or that PHP can set properties, but if there's logic of any kind, then it certainly _might_ be worth testing. It depends. This one specifically, no. – Jonnix Jan 25 '19 at 14:58
  • @JonStirling This is almost literal example. Im already convinced that this test is redundant. – fghjkdfghjrghjk Jan 25 '19 at 15:02
  • I'd test that the constructor can take an argument and that it sets that argument as expected, but that's a difference test. In this case, `$testSubject` can't be anything *but* an instance of Person. (I.e., either you get an object or you get an exception.) – Alex Howansky Jan 25 '19 at 15:04
  • Testing the object type is pointless (IMHO) but you can check that the constructor has done it's job (as already mentioned) using something like https://stackoverflow.com/questions/8928905/phpunit-doing-assertions-on-non-public-variables – Nigel Ren Jan 25 '19 at 15:13
  • 3
    By testing the `__toString` you'll be testing the constructor anyway – Claudio Jan 25 '19 at 15:18
  • @claudio, problem is that your also relying on the fact that `__toString()` works properly, so (being pedantic) your testing more than the constructor working correctly. – Nigel Ren Jan 25 '19 at 15:27
  • @NigelRen isn't that what happens with private methods? – Claudio Jan 25 '19 at 15:32
  • 2
    In TDD you could create a test for the creation of an object in an early stage. But it will be deleted when a new -and better- test covers this creation. – Sven van Zoelen Jan 25 '19 at 20:50

0 Answers0