我想测试一个由库的非 public 异常触发的失败案例。我该如何抛出这个异常?
I want to test a failure case which is triggered by a library's non-public exception. How do I throw this exception?
Tinkerforge 库抛出 TimeoutException
和 NotConnectedException
(以及其他)。我想把这些放在我的测试用例中,这样我就可以测试我的错误处理代码是否正常工作。
当我尝试时
when(brickletLEDStripMock.getRGBValues(any(), any())).thenThrow(new NotConnectedException("Test"));
IntelliJ 告诉我异常不是 public 并且不能从包外访问。
有没有办法扔掉它,也许用 Powermock?
编辑:
感谢 Fran Montero 我现在得到了这个工作代码:
Constructor<NotConnectedException> constructor;
constructor = NotConnectedException.class.getDeclaredConstructor();
constructor.setAccessible(true);
NotConnectedException exception = constructor.newInstance();
when(brickletLEDStripMock.getRGBValues(anyInt(), anyShort())).thenThrow(exception);
您可以使用反射访问 class api:
Constructor<Foo> constructor;
constructor = Foo.class.getDeclaredConstructor(Object.class);
constructor.setAccessible(true);
Foo<String> foo = constructor.newInstance("arg1");
勾选Java: accessing private constructor with type parameters
Tinkerforge 库抛出 TimeoutException
和 NotConnectedException
(以及其他)。我想把这些放在我的测试用例中,这样我就可以测试我的错误处理代码是否正常工作。
当我尝试时
when(brickletLEDStripMock.getRGBValues(any(), any())).thenThrow(new NotConnectedException("Test"));
IntelliJ 告诉我异常不是 public 并且不能从包外访问。
有没有办法扔掉它,也许用 Powermock?
编辑:
感谢 Fran Montero 我现在得到了这个工作代码:
Constructor<NotConnectedException> constructor;
constructor = NotConnectedException.class.getDeclaredConstructor();
constructor.setAccessible(true);
NotConnectedException exception = constructor.newInstance();
when(brickletLEDStripMock.getRGBValues(anyInt(), anyShort())).thenThrow(exception);
您可以使用反射访问 class api:
Constructor<Foo> constructor;
constructor = Foo.class.getDeclaredConstructor(Object.class);
constructor.setAccessible(true);
Foo<String> foo = constructor.newInstance("arg1");
勾选Java: accessing private constructor with type parameters