Thursday, May 31, 2007

Testing: When are Unit tests enough?

I recently received the question: When are Unit tests enough. More specifically, when is it unnecessary to create a Functional test.

I think the case is rare, but I believe it's when the method under test executes entirely in isolation. Put another way, if the method under test doesn't interact in any way with dependent classes or instances, it may be sufficient to Unit test it exclusively.

An example of a method that can execute entirely in isolation is the humanize method defined in rails.
  def humanize(lower_case_and_underscored_word)
lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
end
The humanize method is so focused that it manipulates a string and returns the result. I see no need in Functional testing a method that executes at this level of isolation.

Again, I do believe this is rarely the case. Much more often methods interact with instances of other classes (dependencies). Any time you are interacting with dependencies it's important to verify the integration between classes.

2 comments:

  1. Anonymous11:31 AM

    You need enough of a higher-level test, be that a functional test or something else, to prove that your well-tested humanize method is actually being used. Mocks are a decent way to get there.

    The larger the project, the greater the chance that some otherwise well-tested piece of functionality gets orphaned, with nobody noticing.

    ReplyDelete
  2. Anonymous6:10 PM

    You need enough of a higher-level test, be that a functional test or something else, to prove that your well-tested humanize method is actually being used.

    Correct.

    Jay isn't asserting that there will be no functional tests that reference this method; there are bound to be other entities that are dependent on this method, or else it wouldn't have been written.

    Jay's point is that the method doesn't create any dependencies of its own, and so there aren't any functional tests "owned" by the method.

    ReplyDelete

Note: Only a member of this blog may post a comment.