java 不能用 powermock 子类化最终类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43649973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot subclass final class class with powermock
提问by mrs
I have a "final" class, in which I need to test private methods, tried the following way for the failure case to get (Exception) but getting error
我有一个“最终”类,我需要在其中测试私有方法,尝试了以下方法获取失败情况(异常)但出现错误
[junit] Caused by: IllegalArgumentException: Cannot subclass final class class
[junit] 引起:IllegalArgumentException:无法子类化最终类
How to resolve this error, can anyone please suggest
如何解决此错误,任何人都可以提出建议
//final class
public final Class Test {
//private constructor
private Test(Events event) {
//initialization
}
private JSONObject getReg() {
return new JSONObject;
}
private State Updation(String macAddr) {
try {
return update(getReg(), PATH, macAddr);
} catch (Exception e) {
throw new JSONException(e);
}
}
}
@PrepareForTest({Test.class})
@RunWith(PowerMockRunner.class)
public class TestClassTest {
@Test(expected = Exception.class)
public void UpdationInvalidTest() throws Exception {
JSONObject jsonObj = new JSONObject();
Test test = Whitebox.invokeConstructor(Test.class, event);
Test testSpy = PowerMockito.spy(test);
PowerMockito.doReturn(jsonObj).when(testSpy, "getReg");
Whitebox.invokeMethod(test, "Updation", "00:00:00:00:00:00");
}
}
回答by Mathias Pahlen
As @Ivan says, you should mock a final class. You can accomplish this like so:
正如@Ivan 所说,你应该模拟最后一堂课。您可以像这样完成此操作:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Test.class)
public class TestClassTest {
@Mock
private Test test;
@Test(expected = Exception.class)
public void UpdationInvalidTest() throws Exception {
JSONObject jsonObj = new JSONObject().put("status", 123)
.put("update-time", 123);
Mockito.when(test.getReg()).thenReturn(jsonObj);
}
}
回答by Ivan Pronin
You are getting error when trying to create a spy on a final class. You should use another approach to accomplish this - using mocks as described here: https://github.com/powermock/powermock/wiki/MockFinal:
尝试在最后一堂课上创建间谍时遇到错误。您应该使用另一种方法来完成此操作 - 使用此处描述的模拟:https: //github.com/powermock/powermock/wiki/MockFinal: