This is my code which I want to force to throw a Remote Exception:
transient Bicycle b=null;
public Bicycle getBicycle() {
if(b==null) {
try {
b=new Bicycle(this);
} catch (RemoteException ex) {
Logger.getLogger(Bicycle()).log(Level.SEVERE, null, ex);
}
}
return b;
}
Here is the JUnit test I am running with Mockito:
boolean exceptionThrown=false;
Bicycle mockB = mock(Bicycle);
mockB.setBicycle(null);
stub(mockB.getBicycle()).toThrow(new RemoteException(){boolean exceptionThrown = true;});
assertTrue(exceptionThrown);
I keep receiving the following error:
Checked exception is invalid for this method!
Any help will be appreciated.
Edit:
Instead of
stub(mockB.getBicycle()).toThrow(new RemoteException(){boolean exceptionThrown = true;});
I have also tried
doThrow(new RemoteException(){boolean exceptionThrown = true;}).when(mockB).getBicycle();
and
Mockito.when(mockB.getBicycle()).thenThrow(new RemoteException(){boolean exceptionThrown=true;});
Still no luck.
Edit2 - gone one step further after fully understanding the API and using it correctly:
when(mockB.getBicycle()).thenThrow(new RuntimeException());
I don't know how to make the assert now. I tried putting a boolean once the exception gets called but the assert cannot see the boolean.
Any ideas?
The getBicycle() method will never return a RuntimeException. The code itself is catching the RuntimeException and, when caught, writes to the logger. The method itself will either return the Bicycle or null.
You will need to rethink how you want the getBicycle method operates. It could re-throw the RuntimeException atfer logging if you want the RuntimeException to bubble through. But, based on how that's written, the RuntmeException will never make it out to the JUnit test