我有一个" final" class,我需要测试私有方法, 尝试以下方式获取失败案例(Exception)但得到错误
[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");
}
}
答案 0 :(得分:3)
正如@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);
}
}
答案 1 :(得分:0)
尝试在最终课程中创建间谍时遇到错误。您应该使用另一种方法来实现此目的 - 使用此处所述的模拟:https://github.com/powermock/powermock/wiki/MockFinal: