2

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);
Community
  • 1
  • 1
Kirby
  • 303
  • 2
  • 16

1 Answers1

2

You can access that class using reflection api:

Constructor<Foo> constructor;
 constructor = Foo.class.getDeclaredConstructor(Object.class);
 constructor.setAccessible(true);
 Foo<String> foo = constructor.newInstance("arg1");

Check Java: accessing private constructor with type parameters

Community
  • 1
  • 1
Fran Montero
  • 1,679
  • 12
  • 24