mercredi 5 août 2015

I want to test a failure case which is triggered by a library's non-public exception. How do I throw this exception?

The Tinkerforge library throws TimeoutException and NotConnectedException (among others). I'd like to throw these in my test case, so I can test that my error-handling code works correctly.

When I try

when(brickletLEDStripMock.getRGBValues(any(), any())).thenThrow(new NotConnectedException("Test"));

IntelliJ tells me that the exception is not public and cannot be accessed from outside the package.

Is there a way to throw it anyway, maybe with Powermock?

EDIT:

Thanks to Fran Montero I now got this working code:

Constructor<NotConnectedException> constructor;
constructor = NotConnectedException.class.getDeclaredConstructor();
constructor.setAccessible(true);
NotConnectedException exception = constructor.newInstance();

when(brickletLEDStripMock.getRGBValues(anyInt(), anyShort())).thenThrow(exception);

Aucun commentaire:

Enregistrer un commentaire