PowerMockito ClassNotPreparedException

萝らか妹 提交于 2019-12-08 04:18:24

It seems like you're missing the PowerMockRule declaration:

@Rule
public PowerMockRule rule = new PowerMockRule();

Also, keep in mind that you should let Powermock know that it shouldn't load mockito classes to the system class loader. Add the following code at the top of your class:

@PowerMockIgnore({"org.mockito.*"})

Your class declaration should look like this:

@PrepareForTest(PanelManager.class)
@RunWith(MockitoJUnitRunner.class)
@PowerMockIgnore({"org.mockito.*"})
public class ControllerTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();
    //...
}

You have to use the PowerMockRunner instead of the MockitoJUnitRuner.

This example addresses the ClassNotPreparedException:

@RunWith(PowerMockRunner.class)
@PrepareForTest({PanelManager.class})
public class ControllerTest {

    Controller controller = Mockito.mock(Controller.class);

    @Test
    public void testcreatePanel() throws Exception {
        HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
        HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
        HttpSession hs = Mockito.mock(HttpSession.class);

        PrintWriter writer = new PrintWriter("somefile.txt");
        Mockito.when(res.getWriter()).thenReturn(writer);

        PowerMockito.mockStatic(PanelManager.class);
        PowerMockito.doCallRealMethod().when(controller).createPanel(req, res, hs);
    }
}

However, it looks like there might still be some issues even after that; you are mocking Controller and then treating it as a partial mock by invoking doCallRealMethod() on it. Perhaps there is a genuine reason for this (maybe that reason would be revealed by showing more of your code) but if you do not have a genuine reason for that then you could remove this line:

Controller controller = Mockito.mock(Controller.class);

And replace this line ...

PowerMockito.doCallRealMethod().when(controller).createPanel(req, res, hs);

with this:

Controller.createPanel(req, res, hs);

This would then allow you to mock the behaviour of PanelManager and test the actual behaviour of Controller in response to the PanelManager's mocked behaviour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!