Reputation: 159
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);
$this->assertAttributeEquals($name, 'name', $foo);
}
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. But...
There is a saying: "One assertion per test", so, if my constructor had 6 parameters, I'm going to need 6 assertions an 6 getters to tests theses methods publicly.
Which option you would use?
Upvotes: 4
Views: 2731
Reputation: 278
Before anything you must ask yourself: what's the purpose of testing the constructor? What are you really trying to achieve by doing that?
If what you want is to isolate each method on separated test you should go with option #2 (option #1 also call your getters) but I really think that, in a "real life" project, there's no value to test the constructor.
The constructors just tells how the object should be built and you shouldn't have so much logic on it and all of your tests depends on the constructor so if it's not working your tests will fail.
If you have logic on the constructor you could use named constructors to make things simpler (and yes test them).
P.S.1: Don't forget that accessors are not so good and you should really think wisely before adding them (especially the setters). We should always be focused on the behaviours and not the state of the objects.
P.S.2: Option #2 should be like this:
public function testConstructWorksProperly()
{
$id = 1;
$name = 'name';
$foo = new Foo($id, $name);
$this->assertAttributeEquals($id, 'id', $foo);
$this->assertAttributeEquals($name, 'name', $foo);
}
Upvotes: 6