Testing Within and Outside of Contract
Find out why you need to test exceptions.
Introduction
Every method has a set of circumstances or preconditions allowing it to terminate normally. However, sometimes, there are circumstances and preconditions where the method does not behave as usual. An exception is something that is raised by a called method when a particular set of conditions is met. Exceptions are raised when a method identifies an external problem that prevents it from exiting normally.
Note: On rare occasions, exceptions can also be used for internal issues as well.
Throwing exceptions, without handling them, is useful because it tells you something went wrong. Handling these exceptions through the use of exception handling is even more helpful. Exception handling is the process of responding to raised exceptions.
Understanding exception handling is crucial for designing test cases that test for exceptions. This lesson will focus on exception handling, and the next lesson will focus on how to test for exceptions.
When to use exceptions
Every method has a purpose, for example, sorting a list, finding the maximum number, or calculating an average. Furthermore, every method has circumstances where it can’t do what it is supposed to do. For instance, if the method takes a reference variable as a parameter and that variable points to null, the method can’t be expected to do anything useful with that variable. In these instances, it should throw an exception.
Another way to think about exceptions is to think of methods as having contracts with the caller. If my method signs a contract with its caller that it will deliver on agreements A, B, and C, under which conditions will it not meet these agreements?
Raising exceptions centers around the caller-callee relationship. The caller expects certain things as advertised by the callee. If those results are not met, the callee must know about it. If it doesn’t know about it, the caller will proceed, as usual, not knowing there is a problem.
Get hands-on with 1400+ tech skills courses.