Given the following methods:
public function setFoo($foo) {
$this->_foo = $foo;
return $this;
}
public function getFoo() {
return $this->_foo;
}
Assuming, they may be changed to be more complex in the future:
- How would you write unit tests for those methods?
- Just one test method?
- Should I skip those tests?
- What about code coverage?
- How about
@coversannotation? - Maybe some universal test method to implement in the abstract test case?
(I use Netbeans 7)
This seems like a waste of time, but I wouldn’t mind if IDE would generate those test methods automatically.
To qoute from the comment of Sebastian Bergman’s blog:
(it’s like testing getters and setters — fail!). In any case, if they were to fail; wouldn’t the methods that depend on on them fail?
So, what about the code coverage?
Good Question,
i usually try not to test getters&setters directly since i see a greater benefit in testing only the methods that actually do something.
Especially when not using TDD this has the added benefit of showing me setters that i don’t use in my unittests showing me that ether my tests are incomplete or that the setter is not used/needed. “If i can execute all the “real” code without using that setter why is it there.”
When using fluent setter i sometimes write a test checking the ‘fluent’ part of the setters but usually that is covered in other tests.
To answer your list:
That is my least favorite option. All or none. Testing only one is not easy for other people to understand and looks ‘random’ or needs to be documented in a way.Edit after comment:
Yes, for “trivial” get/set testing I’d only use one method per property maybe depending on the case even only one method for the whole class (for value objects with many getters and setters I don’t want to write/maintain many tests)
I wouldn’t skip them. Maybe the getters depending on how many you have (i tend to write only getters i actually need) but the task of having a class completely covered shouldn’t fail because of getters.
With
@coversmy take is always “use it everywhere or don’t use it at all”. Mixing the two ‘styles’ of testing takes away some of the benefits of the annotation and looks ‘unfinished’ to me.For something like value objects that could work nicely. It might break (or gets more complicated) once you pass in objects / array with type hinting but I’d presonally prefer it over writing manual tests for 500 getters and setters.