For today’s blog post, I wanted to cover a specific topic that I don’t particularly enjoy. While that may sound counterintuitive, I feel that it is important to repeatedly work on skills, even if they aren’t your favorite to practice. So for today’s post, I found an article on imalittletester.com about using try/catch blocks in testing. I don’t particularly enjoy try/catch blocks even though they are incredibly useful and necessary. The author explains multiple scenarios that may occur with try/catch blocks, ensuring that false positives are avoided. She dives into the scenarios, using pseudocode to illustrate what a method may look like for each scenario, and examines how tests must be constructed for each scenario to test the proper criteria.
One of her examples, the scenario where a test should only pass if an exception is not thrown is probably my favorite. She explains that the try/catch block isn’t really needed in this scenario because if we are testing that an exception is not thrown, code without a try/catch block would fail just the same as the try/catch block. This is one less scenario that I’ll have to use the dreaded try/catch blocks.
In my opinion, the most confusing of the four scenarios is how to write a try/catch block where a test should only pass if the exception is thrown. The author explains that what must be done to ensure your test works properly is to have a marker in the try block that will execute if and only if the code that is supposed to throw the exception, doesn’t throw the exception. When executing this try/catch block, the only time that this marker will execute, is when your test is failing. The author explains this in a way that is clear, and easy to follow even for those of us who have such a dislike for try/catch blocks.
In all honesty, I’m glad that I chose this article. I try (no pun intended) to avoid using try/catch blocks as much as a I can, as they can be confusing to me at times. But like I said in the beginning of this post, it is extremely important to practice skills and possibly even more important to practice skills that you don’t particularly like. I will definitely consider this article the next time I’m forced to incorporate try/catch blocks in a program I am writing.
Link to the original article: https://imalittletester.com/2017/04/24/better-test-code-principles-5-mind-your-trycatches/