Java 使用运行时单元测试检查移动连接
我正在尝试为这个方法构建一个单元测试Java 使用运行时单元测试检查移动连接,java,android,unit-testing,testing,runtime,Java,Android,Unit Testing,Testing,Runtime,我正在尝试为这个方法构建一个单元测试 public static boolean isOnline(){ final String command = "ping -c 1 google.com"; boolean isConnected = false; try { isConnected = Runtime.getRuntime().exec(command).waitFor() == 0; } catch (InterruptedExcept
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,我不知道我哪里做错了为什么不使用网络功能检查网络连接?我已经尝试过了,但我也遇到了同样的问题。NetworkCapabilities是最终的/我们无法测试它。顺便说一句,您必须使用androidTest而不是单元测试。