This blog contains reflections and thoughts on my work as a software engineer

torsdag den 17. juli 2008

Antipatterns exception testing

During my first encounters with Test Driven Developement (TDD) I adopted the ExpectedException attribute and used it heavily when coding - that is: I focused a lot on testing for every exception written in the code.

I have come to the conclusion during the last few weeks that my testcases didn't provide very much value if you test heavily for exceptions. There are a few bulletpoints to mention here:


  • Tests written for testing errorconditions on general exceptions (ArgumentNullException etc) are not important. You should write exceptions for ArgumentNull etc. etc but I don't test for them anymore. Focus your testing on things you can assert instead - a test which throws an error will fail the test so even if you don't write an explicit test for the error condition your test will still fail you if the error occurs. Never ever aim for 100% code coverage - if you do you are walking a deathmarch.
  • Business value exceptions are on the other side very important to write tests for. If you have custom exceptions classes which you throw when i.e. a business rule fails to validate you should write a test which succeeds only if the error is thrown. This provides business value: You know that your business logic works because you get your expected exception thrown
  • If you throw exceptions in your code WITHOUT explaining what went wrong I will hunt you down and shoot you in the legs. Not very pedagogic indeed but exceptions are only useful with a meaningful description of what went wrong. You are giving the consumer of the exception no data to help figuring out what went wrong.
Which best practices on this issue do you reccommend to others?

Ingen kommentarer: