Reputation: 1630
In the getUsers method, it invokes an RestTemplate with remote api service. In the code, I want to mock that it throws exception. Then I hard code with throw new Exception("read failed")
.
I know that the code below 'throws' will not be reachable. But I guess this should be only a warning in Intellij idea as the same as VisualStuido does with C#. But here it is an compile error.
Is there any way to suppress this compile error? Because I want to mock an exception here. Thanks.
Edit: Thanks all you guys! Yes, I am trying to insert some temporary debug code, not production code. I will remove the "throws" code once my debug is done.
Upvotes: 0
Views: 1173
Reputation: 140633
Misconception: it is an error, and that is simply what the Java language spec wants it to be, see here:
It is a compile-time error if a statement cannot be executed because it is unreachable.
And you are going down the wrong rabbit hole: you shouldn't try to work around this "warning". When your production code has to throw that exception, then there is zero sense in having other code follow that throws
statement in your production code.
If you want to do some sort of mocking, all of that should happen in your "test" code base.
In other words: to enable yourself to test that catch block, what you could do: extract the part in the try block in a class of its own. Then pass a mocked instance of that class to your production code, and have that mock throw when calling a method on it.
Sometimes it is pragmatic to make slight changes to production code for testability (for example to make methods not private, to allow for access in the same package for test code). But your idea goes way beyond that. So: don't waste your time working around the error.
Upvotes: 2
Reputation: 49656
Is there any way to suppress this compile error?
No. You can remove these 7 lines or comment them out. An exception is thrown unconditionally so there is no way the code below will ever be executed.
I am strongly against introducing a dummy condition to trick the compiler. You can fool the compiler, but you can't fool the developers that will be maintaining the codebase after you.
Upvotes: 2
Reputation: 1575
Yes, unreachable code is a compilation error in Java, not just a warning. The code inspection does not "look" into conditionals, so you can simply do the following:
if (true)
throw new MyException();
Upvotes: 4
Reputation: 13581
No because it's compiler error - use dummy condition like
if(true) {
throw new Exception("read failed");
}
but also consider mocking this method using Mockito or some dummy mock implementation - you will be able then to create proper unit test - such "testing" is rather bad idea and will not help you in the future (just imagine adding such lines every time you will change something and need to test again)
Upvotes: 2