java - 使用运行时单元测试检查移动连接
问题描述
我正在尝试为此方法构建单元测试
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,我不知道我在哪里做错了
解决方案
推荐阅读
- java - 父子组件中的多个 API 调用反应
- javascript - 如何通过 JavaScript 限制输入标签中的数量?
- mysql - Magento 1.x - 一般错误:1813 表空间存在(Google Cloud SQL)
- mongodb - 原因:java.lang.InterruptedException:在使用 JPA 和 Spring Data 的 Mongo 保存操作期间为 null
- deployment - 在 Vercel 中部署 Strapi
- node.js - 如何从头开始实现乐观锁?
- java - JUnit 无法在打包为 JAR 的 Spring Boot 应用程序中以编程方式发现测试
- search - Win 10 文件搜索 - 名称参数后的通配符
- php - PHP路由器和nginx配置
- apache-kafka - 识别并查找 Kafka 主题中的特定消息