jeudi 7 janvier 2016

What is the best way to unit test constructors?

I have the following test methods that tests if a constructor works properly:

Option #1

public function testConstructWorksProperly()
{
    $id = 1;
    $name = 'name';
    $foo = new Foo($id, $name);
    $this->assertEquals($id, $foo->getId());
    $this->assertEquals($name, $foo->getNome());
}

Option #2

public function testConstructWorksProperly()
{
    $id = 1;
    $name = 'name';
    $foo = new Foo($id, $name);
    $this->assertAttributeEquals($id, 'id', $foo->getId());
    $this->assertAttributeEquals($name, 'name', $foo->getNome());
}

On the option #1 I need to create getters to assert that the constructor works properly, while in the option #2 I use an assertion that checks if the constructor have set the property correctly.

I'm wondering in always to use option #1 every time I will need to access those properties publicly because I save time and LOC instead of writing another 2 tests for getId and getName.

Using the option two seems like a white-box testing.

Which option you would use?

Aucun commentaire:

Enregistrer un commentaire