I'm trying to test out some code that is wrapped in a try block. I'd really like to test out the two exception cases that could potentially happen but I'm not sure how because I don't have an easy way to create the error cases.
The method in question is included below. Basically it makes a call on another class to resolve an XPath query. The two catch blocks are used to wrap any XPath exceptions we get with a global exception (so the end-user doesn't have to know we're using XPath). Problem is the XPath query is a private final variable (i.e. not something passed in that I could change).
Does anyone have any ideas how you could test something like this?
Well, as far as I can tell, the XPathExpressionException is very unlikely to ever happen, as the expression is a constant.
That keeps you with the XPathFactoryConfigurationException. You probably don't want to test when this exception is thrown, because that's the responsibility of the XPath-library. So what you want to test for is that when that exception is thrown by the thirdparty code, it gets wrapped in your own exception, don't you?
The best way I know to do that is to change your design so that the call to DOMHelper.evaluateXPath is polymorphic, and then to mock that call so that you can decide to simply throw whatever exception you want.
How does that sound?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Sep 12, 2005
Yeah that's pretty much the conclusion I've come to as well. I was already contemplating pulling the interface for DOMHelper out and having a separate impl. This would fit in with that fairly well.
subject: How to Test Exception conditions you can't create