• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to Test Exception conditions you can't create

 
Adam Kreiss
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey folks,

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?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Adam Kreiss
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic