How to make Mockito throw a RemoteException in a JUnit test

This is my code that I want to force to remove the 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 that I run 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 getting the following error:

Checked exception is invalid for this method!

Any help would be appreciated.

Edit:

Instead

stub(mockB.getBicycle()).toThrow(new RemoteException(){boolean exceptionThrown = true;});

I also tried

doThrow(new RemoteException(){boolean exceptionThrown = true;}).when(mockB).getBicycle();

and

Mockito.when(mockB.getBicycle()).thenThrow(new RemoteException(){boolean exceptionThrown=true;});

Still out of luck.

Edit2 - went one step further after fully understanding the API and using it correctly:

when(mockB.getBicycle()).thenThrow(new RuntimeException());

I do not know how to make a statement now. I tried to put a boolean after throwing an exception, but assert cannot see the boolean.

Any ideas?

+1
source share
1 answer

getBicycle() RuntimeException. RuntimeException , , . , null.

, getBicycle. RuntimeException, , RuntimeException . , , , RuntmeException JUnit

+4

All Articles