java - Java 电源模拟单元测试具有 Thread.Sleep 的方法
问题描述
我正在尝试对调用 Thread.sleep 的方法进行单元测试。
public Boolean waitForUpscale(){
String res = someObject.upTheResources();
Thread.sleep(20000);
Boolean status = someObject.checkForStatus();
return status;
}
在测试此测试时,由于Thread.sleep
我必须在测试时避免测试进入睡眠状态,因此测试也会进入睡眠状态。
更新:
我添加了这个测试:
@Test
public void downscaleTest() throws Exception {
when(someservice.downScaleResources()).thenReturn("DONE");
PowerMockito.mockStatic(Thread.class);
doNothing().when(Thread.class, "sleep", anyLong());
Boolean res = Whitebox.invokeMethod(myController, "downscaleALL");
assertTrue(res);
}
当我调试它时,它可以工作。但是当我正常运行测试时,它无法给出以下异常:
0 matchers expected, 1 recorded:
-> at com.mypackage.controller.MyController.downscaleALL(MyControllerTest.java:265)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
添加 downScaleAll 方法
private Boolean downscaleALL() {
try {
String downScaleResources = someservice.downScaleResources();
if (downScaleResources.equals("DONE")) {
Thread.sleep(20000); // 20s
log.info("DOWNSCALING THE RESOURCES NOW");
return true;
}
return false;
} catch (Exception e) {
log.error("Error while downscaling the resources");
log.error(e.toString());
return false;
}
}
解决方案
您应该只模拟您拥有的类型,因此,如果您想模拟对 的调用Thread.sleep()
,您应该将其提取到您拥有的类型(例如ThreadSleeper
)中,因此可以模拟。更好的是,如果可以的话,重写以避免睡眠。睡眠通常是一种代码气味(偷工减料)。
推荐阅读
- javascript - Joi 验证:用户名不能是电子邮件地址
- javascript - 如何使用 javascript 将 xlsx 文件下载到硬盘
- javascript - 如何在反应中获取选择字段的值?
- php - 如果检查文件中的条件存在 PHP
- php - 检查值是否为整数,是否同时为 int 或 string
- hbase - HBase Table.batch() 在减速器中运行时没有响应
- r - 使用 R 中的 str_match 从下一行赋值
- c++ - std::map 可以移动包含的元素吗?
- python - 问:在 python 中创建一个程序来显示指定范围数字的正方形和立方体的表格
- flutter - 怎么投
列出 ?