Collective Wisdom from the Experts 71
uses a third-party API and try to write unit tests for it. Most of the time, you’ll
run into trouble. You’ll find that the code using the API is stuck to it like glue.
There’s no way to impersonate the API classes so that you can sense your code’s
interactions with them, or supply return values for testing.
Over time, this will get better, but only if we start to see testing as a real use
case when we design APIs. Unfortunately, it’s a little bit more involved than
just testing our code. That’s where the Golden Rule of API Design fits in: It’s
not enough to write tests for an API you develop; you have to write unit tests for
code that uses your API. When you follow this rule, you learn firsthand the
hurdles that your users will have to overcome when they try to test their code
independently.
There is no one way to make it easy for developers to test code that uses your
API. static, final, and sealed are not inherently bad constructs. They can be
useful at times. But it is important to be aware of the testing issue and, to do
that, you have to experience it yourself. Once you have, you can approach it as
you would any other design challenge.