首页 > 解决方案 > 使用运行时单元测试检查移动连接

问题描述

我正在尝试为此方法构建单元测试

public static boolean isOnline(){
    final String command = "ping -c 1 google.com";
    boolean isConnected = false;
    try {
        isConnected = Runtime.getRuntime().exec(command).waitFor() == 0;
    } catch (InterruptedException | IOException e) {
        e.printStackTrace();
    }
    return isConnected;
}

但我完全被这个问题困住了。我像这样用 PowerMockito 尝试过

@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class TestConnection {

   @Mock
   private Runtime mockRuntime;

   @Mock
   private  Process process;

   @Test
   public void test() throws InterruptedException {

       String command = "ping -c 1 google.com";

       boolean isConnected = false;

       PowerMockito.mockStatic(Runtime.class);

       try {
           process = mockRuntime.exec("ping -c 1 google.com");
       } catch (IOException e) {
           e.printStackTrace();
       }
       when(process.waitFor()).thenReturn(0);

       if (process.waitFor() == 0){
           isConnected = true;
       }
       Assert.assertThat(isConnected, CoreMatchers.is(Utils.isOnline()));
       // do the rest of your test
   }
}

这是我第一次使用 mockito 和 powerMokito,我不知道我在哪里做错了

标签: javaandroidunit-testingtestingruntime

解决方案


推荐阅读