Mock java.lang.Runtime with PowerMockito

删除回忆录丶 提交于 2019-12-05 11:20:01
Morfic

My bad in the comments, apologies, I had an inner class for the test and that's why I had no trouble. I then realized this and saw your @PrepareForTest(Runtime.class) which should read @PrepareForTest(MyClass.class) (replace MyClass with whatever name you have) because Runtime is a system class. You can read more about this here and find more examples here.

You must write a wrapper class for Runtime, because it's system class.

public class AppShell {
  public Process exec(String command) {
    return Runtime.getRuntime().exec(command);
  }
}

Then in unit test, use @PrepareForTest(AppShell.class) instead of @PrepareForTest(Runtime.class)

@RunWith(PowerMockRunner.class)
@PrepareForTest(AppShell.class)
public class AppShellTest {

    @Mock private Runtime mockRuntime;

    @Test
    public void test() {
        PowerMockito.mockStatic(Runtime.class);

        when(Runtime.getRuntime()).thenReturn(mockRuntime);
        when(mockRuntime.exec()).thenReturn("whatever you want");

        // do the rest of your test
    }
}

See PowerMock - Mocking system classes

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