← Back to team overview

launchpad-dev team mailing list archive

Re: setUp in unit tests: mostly harmful

 

Hi Henning,

On Thu, Apr 7, 2011 at 1:15 PM, Henning Eggers
<henning.eggers@xxxxxxxxxxxxx> wrote:
> just in case you didn't know about this anti-pattern I created a blog post
> about it. Feel free to applaud or correct. ;-) http://bit.ly/eyEfp7

I feel the same way about setUp.  It's a useful tool, but the most
important thing is that a test should be readable as easily as
possible.  The indirection involved with setUp usually impedes this
goal.

Something missing from the examples in your blog post, that often gets
overlooked, is good test docstrings.  The docstring should be a
statement about the behaviour that is expected, whereas the test code
should demonstrate that the expected behaviour happens.  For example,
I think this test has a good docstring that helps make the code
understandable (from lp:kanban):

    def test_needs_review(self):
        """
        A L{Bug} with an L{IN_PROGRESS} status and a merge proposal with a
        L{NEEDS_REVIEW} status is in the 'Needs review' category.
        """
        bug = Bug("1", "kanban", MEDIUM, IN_PROGRESS, "A title",
                  merge_proposal="url", merge_proposal_status=NEEDS_REVIEW)
        self.assertFalse(bug.queued())
        self.assertFalse(bug.in_progress())
        self.assertTrue(bug.needs_review())
        self.assertFalse(bug.needs_testing())
        self.assertFalse(bug.needs_release())
        self.assertFalse(bug.released())

The combination of the docstring and the code make the test easy to
understand.

Thanks,
J.



References