I have a interface in our code base that I would like to be able to mock out for unit testing. I am writing a test implementation to allow the individual tests to be able to override the specific methods they are concerned with rather than implementing every method.

I've run into a quandary over how the test implementation should behave if the test fails to override a method used by the method under test. Should I return a "non-value" (0, null) in the test implementation or throw a UnsupportedOperationException to explicitly fail the test?


My preference would always be for the exception to be thrown. And preferably an exception that isn't used anywhere else, so that you can easily detect it should any of this ever make it into a live code base.

What you call a non-value is only really a non-value in your current context. As soon as that context changes, both 0 and null may become acceptable return values, and then you have a problem. With the exception you will never have this problem. Plus: most testing frameworks allow you to specifically test for exceptions thrown by methods under test.

| improve this answer | |
  • What you've just described is known as a Strict Mock - something that we abandoned somewhere around 2005 as they lead to Fragile Tests. Not a good idea. – Mark Seemann Jun 30 '11 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.