ryeguy
ryeguy

Reputation: 66851

Is testing simple constructors and defaults considered "testing the language", or is it acceptable?

Often times in unit tests I see people testing very simple things that realistically couldn't fail. For example, given the following class:

class Foo
{
    public $var = 'default val1';
    public $var2 = 4;
    public $var3;

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

Pretty simple. $var and $var2 have defaults, and $var3 is initialized through the constructor.

To some, though, this needs 3 tests. Two to check the defaults are initialized, and a third to check $var3 is assigned through the constructor. To me this seems like a waste - it seems like I'm testing the language's implementation of these features.

Is doing test like these a good idea? If so, why?

Upvotes: 2

Views: 48

Answers (3)

Björn Pollex
Björn Pollex

Reputation: 76848

If this behavior is part of the public interface, it should be tested. Client code might rely on $var having this specific value by default. Tests should make sure that it gets noticed if someone changes that.

Upvotes: 0

Grant Crofton
Grant Crofton

Reputation: 9099

Seems like a waste of time to me. Things without logic don't need testing - as long as you test the behaviour well enough, any problems with constructors, setters, etc will be exposed somewhere.

Upvotes: 1

David Thornley
David Thornley

Reputation: 57046

It really isn't worth writing tests to test the compiler, and generally not for really simple code. Not unless you have some sort of external requirement.

However, that doesn't protect against future changes to Foo. If I were writing some other function that relied on that behavior, I'd be very tempted to write a quick test in the tests for that function.

Upvotes: 2

Related Questions