Monday, March 1, 2010

State Based Testing Versus Interaction Based Testing

When I first learned about unit testing and using mocks for interaction testing, I thought it was incredibly cool. Over the past few months I've seen some people write that state based testing should always be favored because interaction based testing requires knowledge of implementation details. I accepted this as true and started to worry that I relied too heavily on interaction tests. However, I recently began to wonder if interaction tests really do require more knowledge of the implementation details than state based tests. Obviously I am not talking about the case of testing a return value. That is the simplest case and really doesn't require any knowledge of the implementation. What I am talking about is doing state based testing by checking a property after a method is run. Is saying "I know that my class has a property X and I know that running Foo() will result in X being equal to 3" so different from saying "I know that my class has an interface that is used to access the database and I know that running Bar() will result in Baz() being called on that interface"? Some might say that the difference is that the property X is part of the public interface and the interface for data access is not. However, if we are using dependency injection to provide the class under test with its data access object (and we all agree that we should be doing that, right?) then the fact that this class needs, and therefore uses, an implementation of IDataAccess is publicly known.

Maybe I am thinking about it the wrong way but I'm no longer worried about my use of interaction based tests.

2 comments:

  1. You're correct in your understanding of interaction tests and publicly known dependencies.

    by the way: welcome to blogging! this is a great post to get started. i wish i could say my first blog post was anything useful. :)

    ReplyDelete
  2. thanks for reading and commenting (it's quite gratifying to know that at least one other person has actually read my post).

    i don't know what your first post was but i'm pretty sure that you've more than made up for whatever it may have lacked.

    ReplyDelete