我有一个"最终"类,我需要测试私人方法,尝试以下方法以获取失败情况(例外(,但出现错误
[junit]由:iLlegalArgumentException引起:无法子类 最终班级
如何解决此错误,任何人都可以建议
//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");
}
}
正如@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);
}
}
尝试在最终类中创建间谍时会遇到错误。您应该使用另一种方法来实现这一目标 - 使用此处所述的模拟:https://github.com/powermock/powermock/powermock/wiki/mockfinal: