0

For testing purposes, at times I'd like to see how my code handles having an unexpected runtime exception thrown, from various parts of the code.

For example, say I have a method like so:

public int getSum(int x, int y)
{
   return x + y;
}

Is there a way for me to cause this method to fail whenever it's called by throwing an exception instead of returning a valid result? I know I could add in explicit code to do this, but I'd like to know if it's possible to replace a method in any class with a new method that just throws an exception at runtime, or something like that ;-) Kind of like how Mockito can do the following:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);

I'd prefer any solutions to not require any extra tools - just the standard JVM. Thanks!

Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
  • Why do you want this during runtime? – Tim Biegeleisen Sep 16 '16 at 12:28
  • 2
    Keep in mind that runtime exceptions are generally intended to communicate flat-out bugs in your software, such as not handling nulls properly. There's nothing in a method like this that should ever be expected to throw an exception, and I can't think of a good reason to simulate it. – chrylis -cautiouslyoptimistic- Sep 16 '16 at 12:43
  • @TimBiegeleisen - My intent is to cause parts of our code to fail in unexpected ways. Kind of like a [Chaos Monkey](http://whatis.techtarget.com/definition/Chaos-Monkey). I can't arbitrarily start adding code to throw random exceptions to key parts of our code, as I dont own all of it - i'm only on one team.... and other teams own major sections. But if I can fake their code failing at runtime in certain ways, from my own code base, then I can test out fail scenarios that they might not have thought of. And I do get that this could probably be done in unit tests, but there might be merit here – Brad Parks Sep 16 '16 at 12:56
  • So this is really an integration test question. You should create real world scenarios which cause these exceptions. Other than this, stick to robust unit testing. I agree with what @chrylis has said. – Tim Biegeleisen Sep 16 '16 at 12:59
  • 1
    Yeah I'll admit I'm not 100% clear on how I'd ultimately use it, but the question itself still stands separately, regardless of how it's ultimately used ;-) Thanks! – Brad Parks Sep 16 '16 at 13:01
  • The only thing you'd be simulating here is actual hardware failure or JVM bugs, which I don't expect you to be able to successfully handle at the individual-machine level. – chrylis -cautiouslyoptimistic- Sep 16 '16 at 18:48

1 Answers1

0

For simple purpose you could try using Invocation Handler : wrap class method calls and throw exception if needed.

For more sophisticated manipulation you can use Java Instrumentation API.

sol25
  • 139
  • 1
  • 8