in reply to How deep should unit tests go?

Do you use "protected" methods to ease your own implementation, or do you document them for others to do their own subclassing? Generally, I consider a "protected" method to be part of the defined interface and therefore worth testing at the point at which it's documented and if you don't document, you should just make them private (whether with the leading "_" convention or actual checks -- that's up to you).

What I often do to test protected methods is to create a subclass that implementes a public wrapper around the protected method:

package Sub::Class; use base 'Super::Class'; sub public_setCreditAmount { shift->setCreditAmount(@_) }

Then I test that calling the protected method fails on an instance of the superclass, but that calling the public wrapper succeeds on an instance of the subclass.

That's functionally the same -- and perhaps even a bit more work -- than just setting a package and @ISA for a limited scope in the test script itself:

# in the test script { package Sub::Class; our @ISA = 'Super::Class'; my $got; eval { $got = $obj->setCreditAmount( @argument ) }; is( $@, q{}, "setCreditAmount called as subclass" ); is( $got, $expected, "setCreditAmount return value correct" ); }

However, since I usually wind up testing other properties of a subclass, too, I tend to just write the subclass object so I can keep adding to it as I need it.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^2: How deep should unit tests go?
by gargle (Chaplain) on Feb 10, 2006 at 08:10 UTC

    What I often do to test protected methods is to create a subclass that implementes a public wrapper around the protected method:

    A great idea!

    I'll just to that :)

    --
    if ( 1 ) { $postman->ring() for (1..2); }